[英]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. 在我正在构建的页面上,需要显示日期(例如:8月15日),或者,如果日期是今天,则只显示时间,例如:晚上10点。
What would be the best way of coaxing that behaviour out of moment.js? 什么是从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). 我希望日期的格式为'd MMM',时间格式为'hA'(如果分钟为0)或'h:mmA'(如果分钟不为0)。
Any ideas on how to approach this? 关于如何处理这个的任何想法? It looks like the calendar() function might be able to support something like that?
看起来calendar()函数可能能够支持这样的东西吗?
You want to use moment.calendar : set everything except sameDay
to d MMMM and sameDay
to h:mmA . 你想使用moment.calendar :将除了
sameDay
之外的所有内容设置为d MMMM ,将sameDay
为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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.