检查当前时间是否在javascript中的特定间隔内 [英] checking if a current time falls in a particular interval in javascript
问题描述
编辑:请注意在答案中引入UTC时间.由于在客户端执行操作会导致不同的时区.
EDIT: Please take care to introduce UTC timing in your answer. Since doing things on client side will lead to different time zones.
在javascript中,我可以按如下方式获取当前时间,小时和分钟:
In javascript, i can get the current time, hour and minute as follows:
var currentTime = new Date();
var currentHour = currentTime.getHours();
var currentMinute = currentTime.getMinutes();
现在,仅当当前时间在固定时间间隔内为false时,我才需要执行任务.
假设有一个fixed time 10:30 AM
.如果current time
是4 hours behind
,current time
或fixed time
的1 hour ahead
,则用户可以执行某些任务.
Now i have to perform a task only if the current time false in an interval with a fixed time.
Say there is a fixed time 10:30 AM
. Users can perform a certain task iff the current time
, is 4 hours behind
the current time
or 1 hour ahead
of the fixed time
.
意味着用户可以在6:30 AM到11:30 AM之间执行任务.
我尝试获取当前时间并进行
I tried getting the current hours and doing
start = fixed_time - 4;
end = fixed_time + 1;
if currentHour< end or currentHour > start{
do some stuff;
}
但是这忽略了会议记录,如何处理呢? 否则,我如何确定当前时间是否在6:30 AM和11:30 AM之间?
But this ignores the minutes, how to take care of that? Otherwise, how could i figure if the current time lies between 6:30 AM and 11:30 AM?
推荐答案
var currentTime = new Date();
var startTime = new Date(2012, 3, 8, 6, 30, 0, 0); //6:30am today
var endTime = new Date(2012, 3, 8, 11, 30, 0, 0); //11:30am today
if ((currentTime.getTime() > startTime.getTime()) && (currentTime.getTime() < endTime.getTime())
{
//current time is between start and end so do what you need to do
}
如果您需要使其更具动态性,则可以
If you need it to be more dynamic you can
var currentTime = new Date();
var startTime = new Date();
startTime.setHours(6);
startTime.setMinutes(30);
var endTime = new Date();
endTime.setHours(11);
endTime.setMinutes(30);
if ((currentTime.getTime() > startTime.getTime()) && (currentTime.getTime() < endTime.getTime())
{
//current time is between start and end so do what you need to do
}
这篇关于检查当前时间是否在javascript中的特定间隔内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!