How to determine if the specific time is between given time range in javascript

折月煮酒 提交于 2019-12-01 03:23:22

问题


i want to check var check_val in between two time var open_time and var close_time

var 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
}

the result is always else part


回答1:


Date.parse() accepts dates in RFC2822 or ISO8601 formats.

In your case, it always returns NaN.

Date.parse("23:30"); // NaN

Using the appropriate Date format works as expected:

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
}



回答2:


You could create your own object to hold time and then write a function which uses it:

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);



回答3:


If you are just comparing times and not dates you could just do a string comparison

if (check_val > open_time && check_val < close_time)


来源:https://stackoverflow.com/questions/24573669/how-to-determine-if-the-specific-time-is-between-given-time-range-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!