[英]Check if the current time with day is between 2 dates in a weekly calendar
There are a ton of different node modules that lets you check if a date is between two other dates.有很多不同的节点模块可以让你检查一个日期是否在另外两个日期之间。 But I cannot find any modules that let me do the same for day and time (without the date).
但是我找不到任何模块可以让我在日期和时间(没有日期)上做同样的事情。 I only have a weekly calendar (Monday - Sunday) and I want to check if a current day (with time) is between two other days (with time without the date).
我只有一个周历(周一 - 周日),我想检查当前日期(有时间)是否在另外两天之间(有时间没有日期)。
Example:
If "now" is Saturday 11:25
Return true if "now" is between Friday 16:00 and Monday 08:00
Return true if "now" is between Saturday 11:00 and Saturday 12:00
Return false if "now" is between Monday 08:00 and Friday 16:00
Return false if "now" is between Wednesday 08:00 and Saturday 10:00
Are there any easy solution for this?有什么简单的解决方案吗?
I would use moment.js plugin: https://momentjs.com/我会使用 moment.js 插件: https://momentjs.com/
let now = moment('6 11:25', 'E HH:mm'); let min = moment('5 16:00', 'E HH:mm'); let max = moment('1 08:00', 'E HH:mm'); if(max.isBefore(min)) max.add(1, 'weeks'); if(now.isBefore(min)) now.add(1, 'weeks'); console.log(now.isBetween(min, max));
<script src="https://momentjs.com/downloads/moment.js"></script>
The question is whether "now" can be placed between two given points in time that are not more than a week apart .问题是“现在”是否可以放在相隔不超过一周的两个给定时间点之间。
The following functions work on "date objects" consisting of a day
(Sunday = 0, Monday = 1, ..., Saturday = 6) and a time
.以下函数适用于由
day
(Sunday = 0, Monday = 1, ..., Saturday = 6) 和time
组成的“日期对象”。 The between
function tries to sort start <= now <= end
after shifting by one week where necessary. function
between
的尝试排序start <= now <= end
在必要时移动一周后。 It returns true
if that is successful.如果成功,则返回
true
。
function before(a, b) {
return a.day < b.day ||
a.day === b.day && a.time < b.time;
}
function oneweeklater(date) {
return {day: date.day + 7, time: date.time};
}
function between(now, start, end) {
if (before(end, start)) end = oneweeklater(end);
if (before(now, start)) now = oneweeklater(now);
return !before(end, now);
}
var now = {day: 6, time: "11:25"};
console.log(between(now, {day: 5, time: "16:00"}, {day: 1, time: "08:00"}),
between(now, {day: 6, time: "11:00"}, {day: 6, time: "12:00"}),
between(now, {day: 1, time: "08:00"}, {day: 5, time: "16:00"}),
between(now, {day: 3, time: "08:00"}, {day: 6, time: "10:00"}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.