本文介绍了Javascript是否适用于不同的日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要设置一个JavaScript函数以仅运行这些天/小时的组合-周日(无),周一(4-5,8-23),周二至周四(0-5,8-23),周五(0-5,8-21),周六(1-3,8-12,16).

I need to set a javascript function to only run only these day/hour combinations - Sun (none), Mon (4-5,8-23), Tue-Thu (0-5,8-23), Fri (0-5,8-21), Sat (1-3,8-12,16).

这是正确的"if"陈述吗?

Is this the correct "if" statement?

var date = new Date();
var hour = date.getHours();
var day = date.getDay();

if (

   (day !== 0)  ||

   (day == 1 &&

       (hour == 4 || hour == 5 ||  hour > 7)    )    ||

   (day > 1 && day < 6 &&

       (hour !== 6 && hour !==7)   )  ||

   (day == 5 &&

       (hour !== 22 && hour !== 23)   )  ||

   (day == 6 &&

       (hour > 0 && hour < 4 || hour > 7 && hour < 13 ||  hour == 16 ))
  )

推荐答案

为简化代码并使其他人更容易理解和调试,请使用日期和小时将应该运行代码的日期放入数组中.因此,星期一4点将被存储为"2_4".然后遍历数组以检查当前日期和时间是否与任何数组值匹配,如果匹配,则执行代码.这是一个示例:

To simplify your code and make it easier for other to understand and debug, put the days the code is supposed to run in an array using the day and hour. So, Monday at 4 o'clock would be stored as '2_4'. Then loop through the array to check if the current day and time matches any of array values, and if it does, execute your code. Here is an example:

var date = new Date();
var hour = date.getHours();
var day = date.getDay();
var combined = day+'_'+hour;

//add additonal days when the code should run
var run_on = ['2_4','2_5','3_0', '3_1'];

for (i = 0; i < run_on.length; i++){
    if (combined == run_on[i]){
    //execute your code
    break;
    }
}

这大大减少了代码,并且如果需要添加或删除任何时间或日期,则可以轻松地做到这一点,而不必每次都重写逻辑.

This reduces the code significantly and if there are any times or dates that need to be added or removed, you can easily do so without having to rewrite your logic every time.

这篇关于Javascript是否适用于不同的日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 04:43