首页 > 解决方案 > 如何查找当前时间是否存在于给定的时间段中并查找日期是否存在于给定的天数数组之间

问题描述

这是我的日子清单

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_fromday_to

例如这里day_from是 5 是星期六和day_to2 星期三所以所需的数组是: ["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);
      }
     }
    }

它没有给出所需的结果。

标签: javascriptangulartypescript

解决方案


我的理解是您希望将数组视为圆形,然后根据“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"]

我想,这就是你想要的。很可能有边缘情况,所以要小心。

Playground 代码链接


推荐阅读