How to Format Post Dates to show Time since Post

Ever wonder how to format your post times to show up like Twitter or Facebook time since post in minutes, hours, etc? Here is an example of a facebook post 5 hrs ago:

hours ago

I recently had to do this for one of my Ionic mobile apps. Here is the function in JavaScript:

function formatTimeSincePost(time) { // SHOW TIME SINCE POST

    var now = new Date();
    var postTime = new Date(Date.parse(time));
    postTime = now.getTime() – postTime.getTime();

    var timeAgo = Math.ceil(postTime/1000/60);
    var displayTime = "" ;

    if ( timeAgo > 1440 ){ // SHOW DAYS
        displayTime = "" + Math.ceil(timeAgo/60/24) + " days" ;
    }
    else if (timeAgo > 59){ // SHOW HOURS
        displayTime = "" + Math.ceil(timeAgo/60) + " hrs" ;
    }
    else { // SHOW MINUTES
        displayTime = timeAgo + " min" ;
    } 

  return displayTime;
}

You can also add months and years easily if you wish. There you go, happy coding.