javascript - 时刻js判断已经过去多少天、几周
问题描述
我不太擅长处理datetime。我将momentjs用于离子应用程序来操纵时间,但我想实现一些我做不到的事情。
我为此使用了一个管道,我想根据过去的天数或几周、几个月或几年来显示。使用相对时间会帮助我喜欢momentjs的fromNow()
方法和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
}
}
如果几秒钟、几分钟或几小时已经过去,直到 24 小时,我将使用该fromNow()
方法,但当几天过去时,我将使用 the calendar()
,如果几周、几个月或几年过去,则使用 this 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')
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")
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
请运行上面的代码片段来查看边界情况的行为,如果它不准确,您可以用分钟进行 diff 并反转流程。
推荐阅读
- javascript - 这在递归中叫什么?
- search - 邻域搜索在 CPLEX 中的应用
- excel - 我无法在 Microsoft Excel 中获取国家/地区的纬度和经度
- python - 为 Python 聊天应用程序开发更复杂和风格化的 GUI
- r - 编织时GGplot从pdf的一侧溢出
- javascript - 在 div 中创建 innerHTML 并从同一个 div 中创建 getAttribute
- python - TypeError:type_of_triangle() 缺少 2 个必需的位置参数:“a”和“b”
- facebook - Facebook帖子嵌入不可滚动
- flutter - 比较从 Firestore 检索的数据的条件
- c++ - 是什么导致 0 和 1 被写入新文件的末尾?C++