The question is how to format a JavaScript Date
as a string stating the time elapsed similar to the way you see times displayed on Stack Overflow.
e.g.
This question is related to
javascript
date-formatting
An ES6 version of the code provided by @user1012181:
const epochs = [
['year', 31536000],
['month', 2592000],
['day', 86400],
['hour', 3600],
['minute', 60],
['second', 1]
];
const getDuration = (timeAgoInSeconds) => {
for (let [name, seconds] of epochs) {
const interval = Math.floor(timeAgoInSeconds / seconds);
if (interval >= 1) {
return {
interval: interval,
epoch: name
};
}
}
};
const timeAgo = (date) => {
const timeAgoInSeconds = Math.floor((new Date() - new Date(date)) / 1000);
const {interval, epoch} = getDuration(timeAgoInSeconds);
const suffix = interval === 1 ? '' : 's';
return `${interval} ${epoch}${suffix} ago`;
};
Edited with @ibe-vanmeenen suggestions. (Thanks!)
Here is a slight modification on Sky Sander's solution that allows the date to be input as a string and is capable of displaying spans like "1 minute" instead of "73 seconds"
var timeSince = function(date) {_x000D_
if (typeof date !== 'object') {_x000D_
date = new Date(date);_x000D_
}_x000D_
_x000D_
var seconds = Math.floor((new Date() - date) / 1000);_x000D_
var intervalType;_x000D_
_x000D_
var interval = Math.floor(seconds / 31536000);_x000D_
if (interval >= 1) {_x000D_
intervalType = 'year';_x000D_
} else {_x000D_
interval = Math.floor(seconds / 2592000);_x000D_
if (interval >= 1) {_x000D_
intervalType = 'month';_x000D_
} else {_x000D_
interval = Math.floor(seconds / 86400);_x000D_
if (interval >= 1) {_x000D_
intervalType = 'day';_x000D_
} else {_x000D_
interval = Math.floor(seconds / 3600);_x000D_
if (interval >= 1) {_x000D_
intervalType = "hour";_x000D_
} else {_x000D_
interval = Math.floor(seconds / 60);_x000D_
if (interval >= 1) {_x000D_
intervalType = "minute";_x000D_
} else {_x000D_
interval = seconds;_x000D_
intervalType = "second";_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
if (interval > 1 || interval === 0) {_x000D_
intervalType += 's';_x000D_
}_x000D_
_x000D_
return interval + ' ' + intervalType;_x000D_
};_x000D_
var aDay = 24 * 60 * 60 * 1000;_x000D_
console.log(timeSince(new Date(Date.now() - aDay)));_x000D_
console.log(timeSince(new Date(Date.now() - aDay * 2)));
_x000D_
You might want to look at humanized_time_span: https://github.com/layam/js_humanized_time_span
It's framework agnostic and fully customizable.
Just download / include the script and then you can do this:
humanized_time_span("2011-05-11 12:00:00")
=> '3 hours ago'
humanized_time_span("2011-05-11 12:00:00", "2011-05-11 16:00:00)
=> '4 hours ago'
or even this:
var custom_date_formats = {
past: [
{ ceiling: 60, text: "less than a minute ago" },
{ ceiling: 86400, text: "$hours hours, $minutes minutes and $seconds seconds ago" },
{ ceiling: null, text: "$years years ago" }
],
future: [
{ ceiling: 60, text: "in less than a minute" },
{ ceiling: 86400, text: "in $hours hours, $minutes minutes and $seconds seconds time" },
{ ceiling: null, text: "in $years years" }
]
}
humanized_time_span("2010/09/10 10:00:00", "2010/09/10 10:00:05", custom_date_formats)
=> "less than a minute ago"
Read the docs for more info.
function dateToHowManyAgo(stringDate){
var currDate = new Date();
var diffMs=currDate.getTime() - new Date(stringDate).getTime();
var sec=diffMs/1000;
if(sec<60)
return parseInt(sec)+' second'+(parseInt(sec)>1?'s':'')+' ago';
var min=sec/60;
if(min<60)
return parseInt(min)+' minute'+(parseInt(min)>1?'s':'')+' ago';
var h=min/60;
if(h<24)
return parseInt(h)+' hour'+(parseInt(h)>1?'s':'')+' ago';
var d=h/24;
if(d<30)
return parseInt(d)+' day'+(parseInt(d)>1?'s':'')+' ago';
var m=d/30;
if(m<12)
return parseInt(m)+' month'+(parseInt(m)>1?'s':'')+' ago';
var y=m/12;
return parseInt(y)+' year'+(parseInt(y)>1?'s':'')+' ago';
}
console.log(dateToHowManyAgo('2019-11-07 19:17:06'));
I achieve this by following method
timeAgo = (date) => {
var ms = (new Date()).getTime() - date.getTime();
var seconds = Math.floor(ms / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
var months = Math.floor(days / 30);
var years = Math.floor(months / 12);
if (ms === 0) {
return 'Just now';
} if (seconds < 60) {
return seconds + ' seconds Ago';
} if (minutes < 60) {
return minutes + ' minutes Ago';
} if (hours < 24) {
return hours + ' hours Ago';
} if (days < 30) {
return days + ' days Ago';
} if (months < 12) {
return months + ' months Ago';
} else {
return years + ' years Ago';
}
}
console.log(timeAgo(new Date()));
console.log(timeAgo(new Date('Jun 27 2020 10:12:19')));
console.log(timeAgo(new Date('Jun 27 2020 00:12:19')));
console.log(timeAgo(new Date('May 28 2020 13:12:19')));
console.log(timeAgo(new Date('May 28 2017 13:12:19')));
function timeSince(date) {
var seconds = Math.floor((new Date() - date) / 1000);
var interval = seconds / 31536000;
if (interval > 1) {
return Math.floor(interval) + " years";
}
interval = seconds / 2592000;
if (interval > 1) {
return Math.floor(interval) + " months";
}
interval = seconds / 86400;
if (interval > 1) {
return Math.floor(interval) + " days";
}
interval = seconds / 3600;
if (interval > 1) {
return Math.floor(interval) + " hours";
}
interval = seconds / 60;
if (interval > 1) {
return Math.floor(interval) + " minutes";
}
return Math.floor(seconds) + " seconds";
}
var aDay = 24*60*60*1000;
console.log(timeSince(new Date(Date.now()-aDay)));
console.log(timeSince(new Date(Date.now()-aDay*2)));
_x000D_
Although the question was asked quite long time ago, writing this answer with hope it will help somebody.
Pass the date you want to start to count from. Using moment().fromNow()
of momentjs: (See more information here)
getRelativeTime(date) {
const d = new Date(date * 1000);
return moment(d).fromNow();
}
If you want to change information provided for dates fromNow you write your custom relative time for moment.
For example, in my own case I wanted to print 'one month ago'
instead of 'a month ago'
(provided by moment(d).fromNow()). In this case, you can write something given below.
moment.updateLocale('en', {
relativeTime: {
future: 'in %s',
past: '%s ago',
s: 'a few seconds',
ss: '%d seconds',
m: '1 m',
mm: '%d minutes',
h: '1 h',
hh: '%d hours',
d: '1 d',
dd: '%d days',
M: '1 month',
MM: '%d months',
y: '1 y',
yy: '%d years'
}
});
NOTE: I wrote my code for project in Angular 6
I have modified Sky Sanders' version. The Math.floor(...) operations are evaluated in the if block
var timeSince = function(date) {
var seconds = Math.floor((new Date() - date) / 1000);
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
if (seconds < 5){
return "just now";
}else if (seconds < 60){
return seconds + " seconds ago";
}
else if (seconds < 3600) {
minutes = Math.floor(seconds/60)
if(minutes > 1)
return minutes + " minutes ago";
else
return "1 minute ago";
}
else if (seconds < 86400) {
hours = Math.floor(seconds/3600)
if(hours > 1)
return hours + " hours ago";
else
return "1 hour ago";
}
//2 days and no more
else if (seconds < 172800) {
days = Math.floor(seconds/86400)
if(days > 1)
return days + " days ago";
else
return "1 day ago";
}
else{
//return new Date(time).toLocaleDateString();
return date.getDate().toString() + " " + months[date.getMonth()] + ", " + date.getFullYear();
}
}
I was looking for an answer to this and almost implemented one of these solutions, but a colleague reminded me to check the react-intl
library since we were already using it.
So adding to the solutions...in the case you are using the react-intl
library, they have a <FormattedRelative>
component for this.
https://github.com/yahoo/react-intl/wiki/Components#formattedrelative
This should properly handle any valid timestamp, including Date.now(), singular units, and future dates. I left out months, but those should be easy to add in. I tried to keep it readable as possible.
function getTimeInterval(date) {_x000D_
let seconds = Math.floor((Date.now() - date) / 1000);_x000D_
let unit = "second";_x000D_
let direction = "ago";_x000D_
if (seconds < 0) {_x000D_
seconds = -seconds;_x000D_
direction = "from now";_x000D_
}_x000D_
let value = seconds;_x000D_
if (seconds >= 31536000) {_x000D_
value = Math.floor(seconds / 31536000);_x000D_
unit = "year";_x000D_
} else if (seconds >= 86400) {_x000D_
value = Math.floor(seconds / 86400);_x000D_
unit = "day";_x000D_
} else if (seconds >= 3600) {_x000D_
value = Math.floor(seconds / 3600);_x000D_
unit = "hour";_x000D_
} else if (seconds >= 60) {_x000D_
value = Math.floor(seconds / 60);_x000D_
unit = "minute";_x000D_
}_x000D_
if (value != 1)_x000D_
unit = unit + "s";_x000D_
return value + " " + unit + " " + direction;_x000D_
}_x000D_
_x000D_
console.log(getTimeInterval(Date.now())); // 0 seconds ago_x000D_
console.log(getTimeInterval(Date.now() + 1000)); // 1 second from now_x000D_
console.log(getTimeInterval(Date.now() - 1000)); // 1 second ago_x000D_
console.log(getTimeInterval(Date.now() + 60000)); // 1 minute from now_x000D_
console.log(getTimeInterval(Date.now() - 120000)); // 2 minutes ago_x000D_
console.log(getTimeInterval(Date.now() + 120000)); // 2 minutes from now_x000D_
console.log(getTimeInterval(Date.now() + 3600000)); // 1 hour from now_x000D_
console.log(getTimeInterval(Date.now() + 360000000000)); // 11 years from now_x000D_
console.log(getTimeInterval(0)); // 49 years ago
_x000D_
Can also use the dayjs relativeTime plugin to solve this.
import * as dayjs from 'dayjs';
import * as relativeTime from 'dayjs/plugin/relativeTime';
dayjs.extend(relativeTime);
dayjs(dayjs('1990')).fromNow(); // x years ago
Here's what I did (the object returns the unit of time along with its value):
function timeSince(post_date, reference)_x000D_
{_x000D_
var reference = reference ? new Date(reference) : new Date(),_x000D_
diff = reference - new Date(post_date + ' GMT-0000'),_x000D_
date = new Date(diff),_x000D_
object = { unit: null, value: null };_x000D_
_x000D_
if (diff < 86400000)_x000D_
{_x000D_
var secs = date.getSeconds(),_x000D_
mins = date.getMinutes(),_x000D_
hours = date.getHours(),_x000D_
array = [ ['second', secs], ['minute', mins], ['hour', hours] ];_x000D_
}_x000D_
else_x000D_
{_x000D_
var days = date.getDate(),_x000D_
weeks = Math.floor(days / 7),_x000D_
months = date.getMonth(),_x000D_
years = date.getFullYear() - 1970,_x000D_
array = [ ['day', days], ['week', weeks], ['month', months], ['year', years] ];_x000D_
}_x000D_
_x000D_
for (var i = 0; i < array.length; i++)_x000D_
{_x000D_
array[i][0] += array[i][1] != 1 ? 's' : '';_x000D_
_x000D_
object.unit = array[i][1] >= 1 ? array[i][0] : object.unit;_x000D_
object.value = array[i][1] >= 1 ? array[i][1] : object.value;_x000D_
}_x000D_
_x000D_
return object;_x000D_
}
_x000D_
I haven't checked (although it wouldn't be hard to), but I think that Stack Exchange sites use the jquery.timeago
plugin to create these time strings.
It's quite easy to use the plugin, and it's clean and updates automatically.
Here's a quick sample (from the plugin's home page):
First, load jQuery and the plugin:
<script src="jquery.min.js" type="text/javascript"></script> <script src="jquery.timeago.js" type="text/javascript"></script>
Now, let's attach it to your timestamps on DOM ready:
jQuery(document).ready(function() {
jQuery("abbr.timeago").timeago(); });This will turn all
abbr
elements with a class oftimeago
and an ISO 8601 timestamp in the title:<abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr>
into something like this:<abbr class="timeago" title="July 17, 2008">about a year ago</abbr>
which yields: about a year ago. As time passes, the timestamps will automatically update.
My solution..
(function(global){
const SECOND = 1;
const MINUTE = 60;
const HOUR = 3600;
const DAY = 86400;
const MONTH = 2629746;
const YEAR = 31556952;
const DECADE = 315569520;
global.timeAgo = function(date){
var now = new Date();
var diff = Math.round(( now - date ) / 1000);
var unit = '';
var num = 0;
var plural = false;
switch(true){
case diff <= 0:
return 'just now';
break;
case diff < MINUTE:
num = Math.round(diff / SECOND);
unit = 'sec';
plural = num > 1;
break;
case diff < HOUR:
num = Math.round(diff / MINUTE);
unit = 'min';
plural = num > 1;
break;
case diff < DAY:
num = Math.round(diff / HOUR);
unit = 'hour';
plural = num > 1;
break;
case diff < MONTH:
num = Math.round(diff / DAY);
unit = 'day';
plural = num > 1;
break;
case diff < YEAR:
num = Math.round(diff / MONTH);
unit = 'month';
plural = num > 1;
break;
case diff < DECADE:
num = Math.round(diff / YEAR);
unit = 'year';
plural = num > 1;
break;
default:
num = Math.round(diff / YEAR);
unit = 'year';
plural = num > 1;
}
var str = '';
if(num){
str += `${num} `;
}
str += `${unit}`;
if(plural){
str += 's';
}
str += ' ago';
return str;
}
})(window);
console.log(timeAgo(new Date()));
console.log(timeAgo(new Date('Jun 03 2018 15:12:19 GMT+0300 (FLE Daylight Time)')));
console.log(timeAgo(new Date('Jun 03 2018 13:12:19 GMT+0300 (FLE Daylight Time)')));
console.log(timeAgo(new Date('May 28 2018 13:12:19 GMT+0300 (FLE Daylight Time)')));
console.log(timeAgo(new Date('May 28 2017 13:12:19 GMT+0300 (FLE Daylight Time)')));
console.log(timeAgo(new Date('May 28 2000 13:12:19 GMT+0300 (FLE Daylight Time)')));
console.log(timeAgo(new Date('Sep 10 1994 13:12:19 GMT+0300 (FLE Daylight Time)')));
My stab at this based on other answers.
function timeSince(date) {
let minute = 60;
let hour = minute * 60;
let day = hour * 24;
let month = day * 30;
let year = day * 365;
let suffix = ' ago';
let elapsed = Math.floor((Date.now() - date) / 1000);
if (elapsed < minute) {
return 'just now';
}
// get an array in the form of [number, string]
let a = elapsed < hour && [Math.floor(elapsed / minute), 'minute'] ||
elapsed < day && [Math.floor(elapsed / hour), 'hour'] ||
elapsed < month && [Math.floor(elapsed / day), 'day'] ||
elapsed < year && [Math.floor(elapsed / month), 'month'] ||
[Math.floor(elapsed / year), 'year'];
// pluralise and append suffix
return a[0] + ' ' + a[1] + (a[0] === 1 ? '' : 's') + suffix;
}
Might be an overkill in this case, but if the opportunity shows moment.js is just awesome!
Moment.js is a javascript datetime library, to use it for such scenario, you'd do:
moment(yourdate).fromNow()
http://momentjs.com/docs/#/displaying/fromnow/
2018 addendum: Luxon is a new modern library and might be worth a look!
from now, unix timestamp param,
function timeSince(ts){
now = new Date();
ts = new Date(ts*1000);
var delta = now.getTime() - ts.getTime();
delta = delta/1000; //us to s
var ps, pm, ph, pd, min, hou, sec, days;
if(delta<=59){
ps = (delta>1) ? "s": "";
return delta+" second"+ps
}
if(delta>=60 && delta<=3599){
min = Math.floor(delta/60);
sec = delta-(min*60);
pm = (min>1) ? "s": "";
ps = (sec>1) ? "s": "";
return min+" minute"+pm+" "+sec+" second"+ps;
}
if(delta>=3600 && delta<=86399){
hou = Math.floor(delta/3600);
min = Math.floor((delta-(hou*3600))/60);
ph = (hou>1) ? "s": "";
pm = (min>1) ? "s": "";
return hou+" hour"+ph+" "+min+" minute"+pm;
}
if(delta>=86400){
days = Math.floor(delta/86400);
hou = Math.floor((delta-(days*86400))/60/60);
pd = (days>1) ? "s": "";
ph = (hou>1) ? "s": "";
return days+" day"+pd+" "+hou+" hour"+ph;
}
}
Answering 10 years old question to help the newcomers.
We can use this package for that javascript-time-ago
// Load locale-specific relative date/time formatting rules.
import en from 'javascript-time-ago/locale/en'
// Add locale-specific relative date/time formatting rules.
TimeAgo.addLocale(en)
// Create relative date/time formatter.
const timeAgo = new TimeAgo('en-US')
timeAgo.format(new Date())
// "just now"
timeAgo.format(Date.now() - 60 * 1000)
// "a minute ago"
timeAgo.format(Date.now() - 2 * 60 * 60 * 1000)
// "2 hours ago"
timeAgo.format(Date.now() - 24 * 60 * 60 * 1000)
// "a day ago"
Changed the function above to
function timeSince(date) {
var seconds = Math.floor(((new Date().getTime()/1000) - date)),
interval = Math.floor(seconds / 31536000);
if (interval > 1) return interval + "y";
interval = Math.floor(seconds / 2592000);
if (interval > 1) return interval + "m";
interval = Math.floor(seconds / 86400);
if (interval >= 1) return interval + "d";
interval = Math.floor(seconds / 3600);
if (interval >= 1) return interval + "h";
interval = Math.floor(seconds / 60);
if (interval > 1) return interval + "m ";
return Math.floor(seconds) + "s";
}
Otherwise it would show things like "75 minutes" (between 1 and 2 hours). It also now assumes input date is a Unix timestamp.
Much readable and cross browser compatible code:
As given by @Travis
var DURATION_IN_SECONDS = {_x000D_
epochs: ['year', 'month', 'day', 'hour', 'minute'],_x000D_
year: 31536000,_x000D_
month: 2592000,_x000D_
day: 86400,_x000D_
hour: 3600,_x000D_
minute: 60_x000D_
};_x000D_
_x000D_
function getDuration(seconds) {_x000D_
var epoch, interval;_x000D_
_x000D_
for (var i = 0; i < DURATION_IN_SECONDS.epochs.length; i++) {_x000D_
epoch = DURATION_IN_SECONDS.epochs[i];_x000D_
interval = Math.floor(seconds / DURATION_IN_SECONDS[epoch]);_x000D_
if (interval >= 1) {_x000D_
return {_x000D_
interval: interval,_x000D_
epoch: epoch_x000D_
};_x000D_
}_x000D_
}_x000D_
_x000D_
};_x000D_
_x000D_
function timeSince(date) {_x000D_
var seconds = Math.floor((new Date() - new Date(date)) / 1000);_x000D_
var duration = getDuration(seconds);_x000D_
var suffix = (duration.interval > 1 || duration.interval === 0) ? 's' : '';_x000D_
return duration.interval + ' ' + duration.epoch + suffix;_x000D_
};_x000D_
_x000D_
alert(timeSince('2015-09-17T18:53:23'));
_x000D_
function timeago(date) {
var seconds = Math.floor((new Date() - date) / 1000);
if(Math.round(seconds/(60*60*24*365.25)) >= 2) return Math.round(seconds/(60*60*24*365.25)) + " years ago";
else if(Math.round(seconds/(60*60*24*365.25)) >= 1) return "1 year ago";
else if(Math.round(seconds/(60*60*24*30.4)) >= 2) return Math.round(seconds/(60*60*24*30.4)) + " months ago";
else if(Math.round(seconds/(60*60*24*30.4)) >= 1) return "1 month ago";
else if(Math.round(seconds/(60*60*24*7)) >= 2) return Math.round(seconds/(60*60*24*7)) + " weeks ago";
else if(Math.round(seconds/(60*60*24*7)) >= 1) return "1 week ago";
else if(Math.round(seconds/(60*60*24)) >= 2) return Math.round(seconds/(60*60*24)) + " days ago";
else if(Math.round(seconds/(60*60*24)) >= 1) return "1 day ago";
else if(Math.round(seconds/(60*60)) >= 2) return Math.round(seconds/(60*60)) + " hours ago";
else if(Math.round(seconds/(60*60)) >= 1) return "1 hour ago";
else if(Math.round(seconds/60) >= 2) return Math.round(seconds/60) + " minutes ago";
else if(Math.round(seconds/60) >= 1) return "1 minute ago";
else if(seconds >= 2)return seconds + " seconds ago";
else return seconds + "1 second ago";
}
I write one with js and python, used in two projects, very nice and simple: a simple library (less then 2kb) used to format date with *** time ago
statement.
simple, small, easy used, and well tested.
npm install timeago.js
import timeago from 'timeago.js'; // or use script tag
use api format
.
Sample:
var timeagoIns = timeago();
timeagoIns .format('2016-06-12');
Also you can render in real-time.
var timeagoIns = timeago();
timeagoIns.render(document.querySelectorAll('time'));
A shorter version as used by Lokely:
const intervals = [
{ label: 'year', seconds: 31536000 },
{ label: 'month', seconds: 2592000 },
{ label: 'day', seconds: 86400 },
{ label: 'hour', seconds: 3600 },
{ label: 'minute', seconds: 60 },
{ label: 'second', seconds: 0 }
];
function timeSince(date) {
const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
const interval = intervals.find(i => i.seconds < seconds);
const count = Math.floor(seconds / interval.seconds);
return `${count} ${interval.label}${count !== 1 ? 's' : ''} ago`;
}
Simple and readable version:
const NOW = new Date()
const times = [["second", 1], ["minute", 60], ["hour", 3600], ["day", 86400], ["week", 604800], ["month", 2592000], ["year", 31536000]]
function timeAgo(date) {
var diff = Math.round((NOW - date) / 1000)
for (var t = 0; t < times.length; t++) {
if (diff < times[t][1]) {
if (t == 0) {
return "Just now"
} else {
diff = Math.round(diff / times[t - 1][1])
return diff + " " + times[t - 1][0] + (diff == 1?" ago":"s ago")
}
}
}
}
This will show you past and previous time formats like '2 days ago' '10 minutes from now' and you can pass it either a Date object, a numeric timestamp or a date string
function time_ago(time) {_x000D_
_x000D_
switch (typeof time) {_x000D_
case 'number':_x000D_
break;_x000D_
case 'string':_x000D_
time = +new Date(time);_x000D_
break;_x000D_
case 'object':_x000D_
if (time.constructor === Date) time = time.getTime();_x000D_
break;_x000D_
default:_x000D_
time = +new Date();_x000D_
}_x000D_
var time_formats = [_x000D_
[60, 'seconds', 1], // 60_x000D_
[120, '1 minute ago', '1 minute from now'], // 60*2_x000D_
[3600, 'minutes', 60], // 60*60, 60_x000D_
[7200, '1 hour ago', '1 hour from now'], // 60*60*2_x000D_
[86400, 'hours', 3600], // 60*60*24, 60*60_x000D_
[172800, 'Yesterday', 'Tomorrow'], // 60*60*24*2_x000D_
[604800, 'days', 86400], // 60*60*24*7, 60*60*24_x000D_
[1209600, 'Last week', 'Next week'], // 60*60*24*7*4*2_x000D_
[2419200, 'weeks', 604800], // 60*60*24*7*4, 60*60*24*7_x000D_
[4838400, 'Last month', 'Next month'], // 60*60*24*7*4*2_x000D_
[29030400, 'months', 2419200], // 60*60*24*7*4*12, 60*60*24*7*4_x000D_
[58060800, 'Last year', 'Next year'], // 60*60*24*7*4*12*2_x000D_
[2903040000, 'years', 29030400], // 60*60*24*7*4*12*100, 60*60*24*7*4*12_x000D_
[5806080000, 'Last century', 'Next century'], // 60*60*24*7*4*12*100*2_x000D_
[58060800000, 'centuries', 2903040000] // 60*60*24*7*4*12*100*20, 60*60*24*7*4*12*100_x000D_
];_x000D_
var seconds = (+new Date() - time) / 1000,_x000D_
token = 'ago',_x000D_
list_choice = 1;_x000D_
_x000D_
if (seconds == 0) {_x000D_
return 'Just now'_x000D_
}_x000D_
if (seconds < 0) {_x000D_
seconds = Math.abs(seconds);_x000D_
token = 'from now';_x000D_
list_choice = 2;_x000D_
}_x000D_
var i = 0,_x000D_
format;_x000D_
while (format = time_formats[i++])_x000D_
if (seconds < format[0]) {_x000D_
if (typeof format[2] == 'string')_x000D_
return format[list_choice];_x000D_
else_x000D_
return Math.floor(seconds / format[2]) + ' ' + format[1] + ' ' + token;_x000D_
}_x000D_
return time;_x000D_
}_x000D_
_x000D_
var aDay = 24 * 60 * 60 * 1000;_x000D_
console.log(time_ago(new Date(Date.now() - aDay)));_x000D_
console.log(time_ago(new Date(Date.now() - aDay * 2)));
_x000D_
Source: Stackoverflow.com