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.<
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