我的数据库中有两次格式化为字符串,它们分别采用上午 8:30 和晚上 9:00 的格式。使用Javascript,我不想获取当前时间,看看我是否在两次时间的范围内。我将如何去做
将
开始、结束和当前时间转换为 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
);
像这样?
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'));