2016-09-29 65 views
0

背景信息如何在JavaScript中比较UTC时间

我表示从数据库查询返回给我,并存储在一个数组这样UTC开始和结束时间值:

[ '9145001323', '08:00', '12:00' ] 

数组中的第二个和第三个值实际分别代表开始时间和结束时间。

问题

我需要的当前时间来比较UTC格式,看它是否位于起始时间/结束时间范围之间。

代码

这是代码,我现在所拥有的,以获得当前日期/时间:

 var currentUTC = ((new Date()).toUTCString()).split(" "); //returns an array like this: [ 'Thu,', '29', 'Sep', '2016', '15:52:32', 'GMT' ] 
     currentUTC[0] =currentUTC[0].substring(0, currentUTC[0].length - 1); //strip off the traling "," in the day of week name. 
     currentUTC[4] =currentUTC[4].substring(0, currentUTC[4].length - 3); //strip off the seconds portion of the time 

什么是当前的小时/分钟,我有我的currentUTC比较的最好方式数组与我的数据库查询中的数据? (让我们将该数组称为“规则”数组)。

我一直在阅读这篇文章Compare two dates with JavaScript

但是,这似乎是比较完整的日期,而我只需要一个小时/分钟比较。

+2

这是可能做到这一点你自己的,但为什么不使用像此刻库,可以处理这个问题的吗?你会有较少的不一致 – Alex

+0

看到这个:http://stackoverflow.com/questions/338463/how-do-i-do-a-date-comparison-in-javascript - 如果你不想写你自己的代码。 – prabodhprakash

+0

@Alex酷。我从来不知道这一点。我发现它可以和节点一起工作......我会试一试 – Happydevdays

回答

1

通过使用momentjs(http://momentjs.com/docs/)它可能是这样的:

var y = [ '9145001323', '08:00', '12:00' ] 

var t1 = moment.utc(y[1], "HH:mm"); 
var t2 = moment.utc(y[2], "HH:mm"); 
var now = moment.utc(); 
if(now.isAfter(t1) && now.isBefore(t2)){ 
    console.log(" in range "); 
}