Maybe too late, but if you don't have a way this could be helpful to your own. You can support on calendar()
which says:
Calendar time displays time relative to a given referenceDay (defaults to the start of today). [...] Note: From version 2.25.0 you can only pass a formats argument, it could be an object of strings and functions.
The defaults for this are:
moment().calendar({
sameDay: '[Today]',
nextDay: '[Tomorrow]',
nextWeek: 'dddd',
lastDay: '[Yesterday]',
lastWeek: '[Last] dddd',
sameElse: 'DD/MM/YYYY'
});
sameElse
is used as the format when the moment is more than a week away from the referenceDay.
And difference()
to get the difference in milliseconds, or in another unit of measurement.
So for cases less than a week (or 7 days) you can use lastWeek
and for those cases more than a week use sameElse
, something like this:
function calendarDate(date) {
return moment(date).calendar({
sameElse: function (now) {
const from = moment(this);
now = moment(now);
const dayDiff = now.diff(from, 'days');
if (dayDiff >= 7 && dayDiff <= 14) {
return '[Last week]';
} else {
const monthDiff = now.diff(from, 'months', true);
if (monthDiff === 0) {
return '[This month]';
}
if (monthDiff > 0 && monthDiff <= 1) {
return '[Last Month]';
}
if (monthDiff > 1) {
if (Number(from.format('YYYY')) - Number(now.format('YYYY')) < 0) {
return `[${from.format('YYYY')}]`;
}
return `[${from.format('MMMM')}]`;
}
}
return '[More than a week]';
},
});
}
console.log(calendarDate('2020-11-01'));
console.log(calendarDate('2020-10-23'));
console.log(calendarDate('2020-09-30'));
<script src="https://momentjs.com/downloads/moment.js"></script>
Also you can return you message directly from the function instead of the "time ago" string.
Remember that this is just an example and you can adjust the ranges according to your needs.