Moment.js - tomorrow, today and yesterday



Moment.js - tomorrow, today and yesterday
I'd like the moment().fromNow() functionality, but when the date is close it is too precise - ex. I don't want it to show 'in 3 hours' but 'today' - so basically with a 'daily' precision.
I tried using the moment().calendar() function, it doesn't format if the date difference is more than 1 day

Answers:



1.You can also do this to get the date for today and tomorrow and yesterday
let today     = moment(new Date());

let tomorrow  = moment(new Date()).add(1,'days');

let yesterday = moment(new Date()).add(-1, 'days');

2.You can customize the way that both the .fromNow and the .calendar methods display dates using moment.updateLocale. The following code will change the way that .calendar displays as per the question:
moment.updateLocale('en', {
    calendar : {
        lastDay : '[Yesterday]',
        sameDay : '[Today]',
        nextDay : '[Tomorrow]',
        lastWeek : '[Last] dddd',
        nextWeek : '[Next] dddd',
        sameElse : 'L'
    }
});
Based on the question, it seems like the .calendar method would be more appropriate -- .fromNow wants to have a past/present prefix/suffix, but if you'd like to find out more you can read the documentation at http://momentjs.com/docs/#/customization/relative-time/.
To use this in only one place instead of overwriting the locales, pass a string of your choice as the first argument when you define the moment.updateLocale and then invoke the calendar method using that locale (eg. moment.updateLocale('yesterday-today').calendar( /* moment() or whatever */ ))

3.I use a combination of add() and endOf() with moment
//...
const today = moment().endOf('day')
const tomorrow = moment().add(1, 'day').endOf('day')

if (date < today) return 'today'
if (date < tomorrow) return 'tomorrow'
return 'later'
//...

4.I have similar solution, but allows to use locales:
let date = moment(someDate); if (moment().diff(date, 'days') >= 1) { return date.fromNow(); // '2 days ago' etc. } return date.calendar().split(' ')[0]; // 'Today', 'yesterday', 'tomorrow'

Post a Comment

0 Comments