Javascript - 如何检查当前时间是否在两个不同的时间之间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18132396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:50:10  来源:igfitidea点击:

Javascript - How to check if current time is between two different times

javascriptjqueryjquery-mobile

提问by Matt

I am trying programmatically check if the current time for my web application is between two predefined times. I don't know how to get the current time and then set variables that store two predefined times. The pseudo code would look like this

我正在尝试以编程方式检查我的 Web 应用程序的当前时间是否在两个预定义时间之间。我不知道如何获取当前时间,然后设置存储两个预定义时间的变量。伪代码看起来像这样

if(currentTime < shiftStart && currentTime <shiftEnd)
{
   shift = 2
}

But how do I declare and setup the variables so the code works correctly.

但是我如何声明和设置变量以使代码正常工作。

回答by Kira

var diff = date.getTime() - (new Date()).getTime();gives you the difference between the time in milliseconds.

var diff = date.getTime() - (new Date()).getTime();以毫秒为单位为您提供时间之间的差异。

var diff1=shiftStart.getTime() - (new Date()).getTime();
var diff2=shiftEnd.getTime() - (new Date()).getTime();

if(diff1 < 0 && diff2 > 0 ) 
{
    shift = 2;
}

回答by Seano666

var now = Date.now();
var time1 = //whatever time1 is
var time2 = //whatever time2 is

if (now > time1 && now < time2)
{
    alert("blah"):
}