Kno*_*ker 3 javascript datetime datetime-format momentjs relative-time-span
我不太擅长处理datetime。我使用momentjs作为离子应用程序来操纵时间,但我想实现一些我无法实现的目标。
我使用了一个管道,我想根据过去了多少天、几周、几个月还是几年来显示。使用相对时间会帮助我,就像momentjsfromNow()的方法和方法calendar()一样。但就我而言,我会有多个.conditions
这是我的管道的示例代码
transform(value: Date | moment.Moment, dateFormat: string): any {
if (moment(value) < moment(value).subtract(7, 'days')) {
return moment(value).format('llll') // Use this format if weeks, months or years has passed
} else if (moment(value) < moment(value).subtract(1, 'days')) {
return moment(value).calendar(); // Use calendar time if 1 day has passed
} else {
return moment(value).fromNow(); // Use relative time if within 24 hours
}
}
Run Code Online (Sandbox Code Playgroud)
如果经过几秒、几分钟或几小时直到 24 小时,我将使用该fromNow()方法,但经过几天后,我将使用该方法calendar(),如果过去了几周、几个月或几年,我将使用该方法format('llll')。
有人能给我一些启发吗?
提前致谢。
据我了解,您需要根据某个特定时刻距 有多远now做出决定。您似乎有 3 种情况:> 7 天,> 1 天,< 1 天。
Momentjs提供了一个非常有用的diff方法。所以,你可以这样做:
var currDate = moment.now();
var dateToTest = moment(val);
// if dateToTest will always be in past, use currDate as the base to diff, else
be prepared to handle the negative outcomes.
var result = currDate.diff(dateToTest, 'days')
Run Code Online (Sandbox Code Playgroud)
var currDate = moment.now();
var dateToTest = moment(val);
// if dateToTest will always be in past, use currDate as the base to diff, else
be prepared to handle the negative outcomes.
var result = currDate.diff(dateToTest, 'days')
Run Code Online (Sandbox Code Playgroud)
window.onload = function() {
console.log("Test Cases: ")
console.log("Input: Date is 2 minutes behind")
dateThing("2018-07-20T12:02:54+00:00");
console.log("Input: Date is few hours behind")
dateThing("2018-07-20T07:02:54+00:00");
console.log("Input: Date is 23 hours 59 minutes behind")
dateThing("2018-07-19T12:03:54+00:00");
console.log("Input: Date is 24 hours behind")
dateThing("2018-07-19T12:04:54+00:00");
console.log("Input: Date is 2 days behind")
dateThing("2018-07-18T12:04:54+00:00");
console.log("Input: Date is 12 days behind")
dateThing("2018-07-08T12:04:54+00:00");
}
dateThing = function(val) {
// for now freezing the "now" so that precise testcases can be written.
// var currDate = moment.now();
var currDate = moment("2018-07-20T12:04:54+00:00")
var dateToTest = moment(val);
// if dateToTest will always be in past, use currDate as the base to diff, else be prepared to handle the negative outcomes.
var result = currDate.diff(dateToTest, 'days')
if (result > 7) {
console.log("Output: date is more than 1 week behind")
} else if (result > 1) {
console.log("Output: date is more than 1 day but less than 1 week behind")
} else {
console.log("Output: date is less than 1 day behind")
}
}Run Code Online (Sandbox Code Playgroud)
请运行上面的代码片段来查看边界情况的行为,如果不准确,您可以在几分钟内进行差异并反转流程。