我想在两个时间var open_time和var close_time
之间检查var check_valvar open_time = "23:30";
var close_time = "06:30";
var check_val ="02:30";
if(Date.parse ( check_val ) > Date.parse ( open_time ) && Date.parse ( check_val ) < Date.parse ( close_time )){
var flag=1;
} else {
var flag=2
}
结果总是其他部分
答案 0 :(得分:3)
Date.parse()
接受RFC2822或ISO8601格式的日期。
在您的情况下,它始终返回NaN
。
Date.parse("23:30"); // NaN
使用适当的日期格式按预期工作:
var open_time = Date.parse("2011-10-09T23:30");
var close_time = Date.parse("2011-10-10T06:30");
var check_val = Date.parse("2011-10-10T02:30");
if( check_val > open_time && check_val < close_time ) {
var flag=1;
} else {
var flag=2
}
答案 1 :(得分:3)
您可以创建自己的对象来保留时间,然后编写一个使用它的函数:
var Time = function(timeString) {
var t = timeString.split(":");
this.hour = parseInt(t[0]);
this.minutes = parseInt(t[1]);
this.isBiggerThan = function(other) {
return (this.hour > other.hour) || (this.hour === other.hour) && (this.minutes > other.minutes);
};
}
var timeIsBetween = function(start, end, check) {
return (start.hour <= end.hour) ? check.isBiggerThan(start) && !check.isBiggerThan(end)
: (check.isBiggerThan(start) && check.isBiggerThan(end)) || (!check.isBiggerThan(start) && !check.isBiggerThan(end));
}
var openTime = new Time("23:30");
var closeTime = new Time("06:30");
var checkTime = new Time("02:30");
var isBetween = timeIsBetween(openTime, closeTime, checkTime);
答案 2 :(得分:0)
如果您只是比较时间而不是日期,那么您可以进行字符串比较
if (check_val > open_time && check_val < close_time)