moment.js - 显示日期或时间

Fat*_*tal 9 javascript momentjs

在我正在构建的页面上,需要显示日期(例如:8月15日),或者,如果日期是今天,则只显示时间,例如:晚上10点.

什么是从moment.js中哄骗这种行为的最好方法?

我希望日期的格式为'd MMM',时间格式为'hA'(如果分钟为0)或'h:mmA'(如果分钟不为0).

关于如何处理这个的任何想法?看起来calendar()函数可能能够支持这样的东西吗?

Fem*_*emi 11

你想用moment.calendar:设置一切,除了sameDayd MMMMsameDayH:MMA.你不能做比这更好的粮食.

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();
}
Run Code Online (Sandbox Code Playgroud)


tim*_*ood 8

你可以写一个微插件来自己做.

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);
}
Run Code Online (Sandbox Code Playgroud)