Moment.js - tomorrow, today and yesterday

2019-03-11 13:42发布

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

9条回答
smile是对你的礼貌
2楼-- · 2019-03-11 13:47

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] ffffdd',
        nextWeek : '[Next] ffffdd',
        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 */ ))

EDIT: Moment ^2.12.0 now has the updateLocale method. updateLocale and locale appear to be functionally the same, and locale isn't yet deprecated, but updated the answer to use the newer method.

查看更多
你好瞎i
3楼-- · 2019-03-11 13:52

You can use this:


const today     = moment();

const tomorrow  = moment().add(1, 'days');

const yesterday = moment().subtract(1, 'days');

查看更多
混吃等死
4楼-- · 2019-03-11 13:56

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');
查看更多
forever°为你锁心
5楼-- · 2019-03-11 13:56

From 2.10.5 moment supports specifying calendar output formats per invocation For a more detailed documentation check Moment - Calendar.

**Moment 2.10.5**
moment().calendar(null, {
  sameDay: '[Today]',
  nextDay: '[Tomorrow]',
  nextWeek: 'ffffdd',
  lastDay: '[Yesterday]',
  lastWeek: '[Last] ffffdd',
  sameElse: 'DD/MM/YYYY'
});

From 2.14.0 calendar can also take a callback to return values.

**Moment 2.14.0**
    moment().calendar(null, {
     sameDay: function (now) {
       if (this.isBefore(now)) {
         return '[Will Happen Today]';
       } else {
        return '[Happened Today]';
       }
       /* ... */
      }
    });
查看更多
Animai°情兽
6楼-- · 2019-03-11 14:01

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

查看更多
唯我独甜
7楼-- · 2019-03-11 14:03

So this is what I ended up doing

var dateText = moment(someDate).from(new Date());
var startOfToday = moment().startOf('day');
var startOfDate = moment(someDate).startOf('day');
var daysDiff = startOfDate.diff(startOfToday, 'days');
var days = {
  '0': 'today',
  '-1': 'yesterday',
  '1': 'tomorrow'
};

if (Math.abs(daysDiff) <= 1) {
  dateText = days[daysDiff];
}
查看更多
登录 后发表回答