免责声明:我对javascript (和角)非常陌生。
从现在到昨天,我正试着让时间显示出来。一旦到了三天,它就会显示实际日期。
使用随机日期的示例(日期差异始终为“今天”):
不知道我应该提供什么其他信息,但请询问是否有任何帮助。
发布于 2017-09-14 05:34:39
谢谢大家的意见。用你的例子,我解决了这个问题。不久后,我找到了一个更好的方式来做我想做的事,我将在这里分享。
使用momentJS日历功能使此操作非常简单。这是我的过滤器,它做的正是我想要的,加上一些额外的功能。
//This filter will display today, tomorrow, yesterday then display the actual date as 'M/D/Y at h:mm a'.
//Default preposition is 'at', but any other can be passed in as the second parameter.
.filter('formatForTimeAgo', function () {
return function timeTodayDateElse(date, preposition){
preposition=preposition|| 'at'
moment.lang('en', {
'calendar' : {
'lastDay' : '[Yesterday] [\n][ '+preposition+' ] h:mm a',
'sameDay' : '[Today] [\n][ '+preposition+' ] h:mm a',
'nextDay' : '[Tomorrow] [\n][ '+preposition+' ] h:mm a',
'lastWeek' : 'M/D/YY [\n]['+preposition+'] h:mm a',
'nextWeek' : 'M/D/YY [\n]['+preposition+'] h:mm a',
'sameElse' : 'M/D/YY [\n]['+preposition+'] h:mm a'
}
});
return moment(date).calendar();
}
})
格式化后的{{yourDate | }}将显示如下:Today at 10:17 pm、Yesterday at 10:17 pm或Tomorrow at 10:17 pm。一次+/- 2天,它将显示为一个数字日期,如9/13/17 at 10:17 pm。
您可以使用第二个参数插入自定义介词(默认为"at")。例如:{{yourDate | formatForTimeAgo : 'by'}}会将"at“改为"by”,这样就可以得到Today by 10:17 pm、Yesterday by 10:17 pm等。
再一次谢谢。这是一次很好的学习经历。
发布于 2017-09-13 02:34:30
有几个函数可以帮助获得预期的输出。
moment.format():你可以用它来格式化你想要的字符串。例如:moment.format("dd/MM/YY at hh:mm:ss")moment.isSame():确定日期是否与今天相同。moment.diff():确定日期之间的差异。下面是一个基于预期输出的解决方案:https://jsfiddle.net/3ruv8aj3/
发布于 2017-09-13 02:39:56
我不知道到目前为止你对这一刻的熟悉程度,所以从一开始就有一个方法可以做到:
// get today's date and time
var now = moment();
// will hold our display string (we'll set this in a minute)
var displayValue = '';
// target date & time in string format (YYYY-MM-DD hh:mm)
// you can also use a JavaScript date object instead of a string
var dateString = '2017-10-10 06:41';
// create a moment wrapper for the past/future date
var targetDate = moment(dateString);
// how many total days difference between then and now?
// calling moment() with no args defaults to current date and time
// first argument to `diff` is the date to subtract
// second argument is the unit of time to measure in
var difference = now.diff(targetDate, 'days');
if (difference > 3 || difference < -3) {
// if the date is more than three days in the past or more than three days into the future...
displayValue = targetDate.format('MM-DD-YYYY') + ' at ' + targetDate.format('hh:mm');
} else {
// otherwise...
displayValue = targetDate.fromNow();
}
console.log(displayValue); // > "10-10-2017 at 06:41"编辑:如果目标日期恰好是今天,并且希望显示“今天”而不是默认的“15小时前”,只需检查差异为0。
if (difference === 0) displayValue = 'Today at ' + targetDate.format('hh:mm');编辑:为“现在”创建了一个变量,以提高清晰度。
https://stackoverflow.com/questions/46187726
复制相似问题