javascript - 如何查找当前时间是否存在于给定的时间段中并查找日期是否存在于给定的天数数组之间
问题描述
这是我的日子清单
days_list: any[] = [
{
id: 0,
value: 'Monday'
},
{
id: 1,
value: 'Tuesday'
}, {
id: 2,
value: 'Wednesday'
}, {
id: 3,
value: 'Thursday'
}, {
id: 4,
value: 'Friday'
}, {
id: 5,
value: 'Saturday'
},
{
id: 6,
value: 'Sunday'
},
]
这是我的营业时间
business_hours = { day_to: 2, time_to: "23:00", day_from: 5, time_from: "08:00" }
我正在使用 UTC 日期格式我想知道days_list
根据day_from
和day_to
例如这里day_from
是 5 是星期六和day_to
2 星期三所以所需的数组是:
["Saturday", "Sunday", "Monday". "Tuesday". "Wednesday"]
如果当前时间存在于time_from
和中,则时间相同time_to
,
我的代码是:
const activationDate = new Date();
const d_date = activationDate.getUTCDay() - 1;
console.log(d_date);
const B_from = this.getMin(this.business_hours.time_from);
const B_To = this.getMin(this.business_hours.time_to);
const min = activationDate.getUTCMinutes();
console.log(min)
const naan = activationDate.getUTCHours();
console.log(naan)
const utcTime = this.getUtcMin(naan, min);
for(let j = 0; j < this.business_hours.day_to; j++) {
for (let i = this.business_hours.day_from; i < this.days_list.length; i++) {
console.log(this.days_list[i]);
if (this.days_list[i].id === d_date) {
this.is_open = true;
console.log(this.days_list[i].value);
}
}
}
它没有给出所需的结果。
解决方案
我的理解是您希望将数组视为圆形,然后根据“from”和“to”索引对其进行切片,其中“from”和“to”索引都被视为inclusive。
假设您有一个这样的字符串数组:
console.log(dayArray);
// ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
(你可以很容易地把你的结构变成:
const dayArray = days_list.reduce<string[]>((a, d) => (a[d.id] = d.value, a), []);
)
然后,您可以通过多种方式编写具有包含端点函数的圆形数组切片。这是一个:
function circularArraySlice<T>(arr: T[], fromIndex: number, toIndex: number) {
return arr.map((_, i, a) => a[(i + fromIndex) % a.length]).
slice(0, ((arr.length + toIndex - fromIndex) % arr.length) + 1);
}
本质上,我们使用模运算(几乎)由JS 余数运算符 ( %
)实现,从数组的末尾走出来并回到开头。让我们看看它是否有效:
console.log(circularArraySlice(dayArray, 5, 2));
// ["Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"]
console.log(circularArraySlice(dayArray, 2, 5));
// ["Wednesday", "Thursday", "Friday", "Saturday"]
我想,这就是你想要的。很可能有边缘情况,所以要小心。
推荐阅读
- django - 在 Django 中,静态文件以引用循环结束的一个很好的例子是什么?
- javascript - 由于 .map 导致测试用例失败不是函数错误
- bash - 打印文件或目录的名称、类型和大小
- javascript - 如何从 KnockoutObservableArray 中搜索和检索结果数组
- javascript - 排序后,dblclick 函数停止工作
- html - 如何仅在一个部分内使用页面滚动菜单?
- apache-spark - Databricks Delta 和 Hive 事务表
- c++ - 没有名为“argument_type”的类型
- elasticsearch - Kibana(elasticsearch 可视化) - 如何根据字段的子字符串添加绘图?
- c# - C#.net 如何完全忽略/消除 datetimepicker 中的日期值?