如何只显示今天'什么都没有?

时间:2015-03-25 09:12:10

标签: momentjs

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

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

1 个答案:

答案 0 :(得分:0)

使用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();将返回"Today"

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

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

没有硬编码的解决方案

我非常喜欢这个解决方案,但它确实依赖于非公开的时刻api,localeData._calendar,因为这个数据没有吸气剂。它还为extend使用jquery,如果你没有使用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获取字符串。