如何只显示 'Today' 而没有其他内容?

How to display just 'Today' with nothing else?

我只想要 'Today' 如果日期时间在今天之内。

moment().calendar()  // 'Today at 5:08PM'

使用 custom locale.

moment.locale('en-cust', {
    calendar: { /*replace calendar format strings*/
        lastDay: '[Yesterday at] LT',
        sameDay: '[Today]', // <---
        nextDay: '[Tomorrow at] LT',
        lastWeek: '[last] dddd [at] LT',
        nextWeek: 'dddd [at] LT',
        sameElse: 'L'
    }
});

在运行之后,moment().calendar();将return"Today"

所有非日历行为都将保持默认的 locale: 'en' 行为。

请注意,您需要替换整个日历对象,而不仅仅是 sameDay 属性。

没有硬编码的解决方案

我非常喜欢这个解决方案,但它确实依赖于非 public momentjs api、localeData._calendar,因为没有 getter 这个数据.它还将 jquery 用于 extend,如果您不使用 jquery,请告诉我。

function correctToday(locale,strf){
    // copy and extend the locale's calendar data
    var localeCal = $.extend({}, moment.localeData(locale)._calendar, {'sameDay':strf});
    // Replace the locale's calendar data with the modified one (uses public setter)
    moment.locale(locale,{calendar:localeCal});
}

// Usage
correctToday('en',"[today]");
correctToday('fr',"[aujourd'hui]");

和一些测试用例:

moment.locale();
moment().calendar(); //test changes
moment().subtract(22,'hours').calendar(); //test other cal functionality
moment().format(); //test non-cal functionality
moment().fromNow();

// Produces
// ["en", "today", "Yesterday at 12:09 PM", "2015-03-26T10:09:05-04:00", "a few seconds ago"]
// ["fr", "aujourd'hui", "Hier à 12:09", "2015-03-26T10:09:05-04:00", "il y a quelques secondes"]

切换

您可以使用函数代替字符串进行区域设置。所以,上面的 correctToday 函数保持不变,但如果我们想要切换,我们可以这样称呼它:

moment.timeOff = true; // this is the toggle, declare it somewhere globally accessible (I'm adding it to moment)
correctToday('en',function(){
    return moment.timeOff ? "[today]" : "[today at] LT";
});

如果您不喜欢 "[today at] LT" 被硬编码,请在更改之前存储原始 localeData._calendar 并从 .sameDay.

中获取字符串