且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用JavaScript将当前时间与格式化为字符串的时间范围进行比较

更新时间:2023-09-05 23:51:52

将开始时间,结束时间和当前时间转换为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
);