2

我在我的数据库中有两次格式化为字符串,它们的格式分别为上午 8:30 和晚上 9:00。使用Javascript,我不想得到当前时间,看看我是否在两次的范围内。我该怎么做

4

2 回答 2

2

将开始、结束和当前时间转换为 JavaScript Date 对象,然后检查是否start <= current < end. 如果开始日期小于结束日期,就会变得很棘手:

// 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
);
于 2012-06-29T21:00:55.600 回答
1

像这样?

function validNow ( from, until ) {
    var toTime= function ( str ) {
        var match = str.match(/^(\d+):(\d+)\s*([AP])/);
        if ( !match ) throw "str has wrong format";
        return match[1] * 60 + +match[2] + (match[3] == 'P' ? 720 : 0);
    };

    var d= new Date();           
    var current= d.getHours() * 60 + d.getMinutes();
    console.log(current, toTime(until));
    return current >= toTime(from) && current <= toTime(until);
}

console.log(validNow('8:30PM', '10:11PM'));
于 2012-06-29T21:03:41.727 回答