How to display just 'Today' with nothing else?

后端 未结 1 1188
慢半拍i
慢半拍i 2021-01-26 02:48

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

moment().calendar()  // \'Today at 5:08PM\'
相关标签:
1条回答
  • 2021-01-26 03:14

    Use a custom locale.

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

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

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

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

    Solution without hardcoding

    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]");
    

    And some test cases:

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

    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";
    });
    

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

    0 讨论(0)
提交回复
热议问题