Moment.js - tomorrow, today and yesterday

后端 未结 12 2215
悲哀的现实
悲哀的现实 2021-01-30 00:21

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 basica

12条回答
  •  不要未来只要你来
    2021-01-30 01:00

    Requirements:

    • When the date is further away, use the standard moment().fromNow() functionality.
    • When the date is closer, show "today", "yesterday", "tomorrow", etc.

    Solution:

    // call this function, passing-in your date
    function dateToFromNowDaily( myDate ) {
    
        // get from-now for this date
        var fromNow = moment( myDate ).fromNow();
    
        // ensure the date is displayed with today and yesterday
        return moment( myDate ).calendar( null, {
            // when the date is closer, specify custom values
            lastWeek: '[Last] ffffdd',
            lastDay:  '[Yesterday]',
            sameDay:  '[Today]',
            nextDay:  '[Tomorrow]',
            nextWeek: 'ffffdd',
            // when the date is further away, use from-now functionality             
            sameElse: function () {
                return "[" + fromNow + "]";
            }
        });
    }
    

    NB: From version 2.14.0, the formats argument to the calendar function can be a callback, see http://momentjs.com/docs/#/displaying/calendar-time/.

提交回复
热议问题