如何使用JavaScript将当前时间与格式化为字符串的时间范围进行比较 [英] How to compare current time to a time range formated as a string using Javascript
本文介绍了如何使用JavaScript将当前时间与格式化为字符串的时间范围进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在数据库中两次将其格式化为字符串,它们的格式分别为8:30 AM和9:00 PM。我希望使用Javascript来获取当前时间,而不是看我是否在两次时间范围内。我该怎么做
I have two times formatted as strings in my database, they are in the format 8:30AM and 9:00 PM respectively. Using Javascript, I wan't to get the current time and see if I am within the rang of the two times. How would I go about doing this
推荐答案
将开始时间,结束时间和当前时间转换为JavaScript Date对象,然后检查开始< =当前<结束
。如果开始日期小于结束日期,则会变得棘手:
Convert the start, end and current time into JavaScript Date objects, then check if start <= current < end
. It gets tricky if the start date becomes less than end date:
// The un-important bits
var d0 = new Date("01/01/2001 " + "8:30 AM");
var d1 = new Date("01/01/2001 " + "9:00 PM");
var d = new Date("01/01/2001");
d.setHours(new Date().getHours());
d.setMinutes(new Date().getMinutes());
// For testing
console.log(d0, d, d1);
// The important bit
console.log(
d0 < d1
? (d0 <= d && d < d1)
: (d1 <= d && d < d0) == false
);
这篇关于如何使用JavaScript将当前时间与格式化为字符串的时间范围进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文