简体   繁体   中英

moment.js - display either date OR time

On a page that I'm building, there is a requirement to either display the date (eg: 15 Aug) or, if the date is today, just display a time, eg: 10pm.

What would be the best way of coaxing that behaviour out of moment.js?

The format i'd like for a date is 'd MMM' and the format for time would be 'hA' (if minutes are 0) or 'h:mmA' (if minutes are not 0).

Any ideas on how to approach this? It looks like the calendar() function might be able to support something like that?

You want to use moment.calendar : set everything except sameDay to d MMMM and sameDay to h:mmA . You can't do finer grain than that.

function timeTodayDateElse(date){
    moment.lang('en', {
        'calendar' : {
            'lastDay' : 'D MMMM',
             'sameDay' : 'h:mmA',
            'nextDay' : 'D MMMM',
            'lastWeek' : 'D MMMM',
            'nextWeek' : 'D MMMM',
            'sameElse' : 'D MMMM'
       }
    });

    return moment(date).calendar();
}

You could write a micro plugin to do this yourself.

moment.fn.formatTimeToday = function () {
    var now = moment(),
        format = "d MMM";
    if (this.date() === now.date() && 
        Math.abs(this.diff(now)) < 86400000) {
        // same day of month and less than 24 hours difference
        if (this.minutes() === 0) {
             format = "hA";
        } else {
             format = "h:mmA";
        }
    }
    return this.format(format);
}

A quick Google search (moment.js relative time) gives this link to the documentation. You should be able to customize this with the format strings you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM