如何只显示“今天"而没有其他内容? [英] How to display just 'Today' with nothing else?

查看:80
本文介绍了如何只显示“今天"而没有其他内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果日期时间在今天之内,我只想今天".

I just want 'Today' if the datetime is within today.

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

推荐答案

使用自定义语言环境.

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

After running that, moment().calendar(); will return "Today".

所有非日历行为都会保留默认的locale: 'en'行为.

All non-calendar behaviour will maintain the default locale: 'en' behaviour.

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

Note that you need to replace the whole calendar object and not just the sameDay property.

我非常喜欢此解决方案,但它确实依赖于非公开的momentjs api,localeData._calendar,因为该数据没有吸气剂.它还为extend使用了jquery,如果您不使用jquery,请告诉我.

I like this solution a lot but it does rely on a non-public momentjs api, localeData._calendar since there isn't a getter for this data. It also uses jquery for extend, let me know if you aren't using 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函数保持不变,但是如果我们想要切换,我们将其命名为:

Toggle

You can use functions in place of strings for locale settings. So, the correctToday function above remains the same but if we want a toggle, we call it like:

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中获取字符串.

If you don't like "[today at] LT" being hardcoded, store the original localeData._calendar before changing it and take the string from .sameDay.

这篇关于如何只显示“今天"而没有其他内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆