Skip to content

Instantly share code, notes, and snippets.

@YugalXD
Created December 15, 2015 11:26
Show Gist options
  • Save YugalXD/1ec3a0b770c34bb15725 to your computer and use it in GitHub Desktop.
Save YugalXD/1ec3a0b770c34bb15725 to your computer and use it in GitHub Desktop.
get relative time in js
function relative_time(date_str) {
if (!date_str) {return;}
var parsed_date = date_str;
var relative_to = (arguments.length > 1) ? arguments[1] : new Date(); //defines relative to what ..default is now
var delta = parseInt((relative_to.getTime()-parsed_date)/1000);
delta=(delta<2)?2:delta;
var r = '';
if (delta < 60) {
r = delta + ' seconds ago';
} else if(delta < 120) {
r = 'a minute ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60, 10)).toString() + ' minutes ago';
} else if(delta < (2*60*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600, 10)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = 'a day ago';
} else {
r = (parseInt(delta / 86400, 10)).toString() + ' days ago';
}
return 'about ' + r;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment