我有startTime和endTime以及current_time,如何检查当前时间是否在这两次之间?
我尝试过如下:
var startTime = '08:27 PM';
var endTime = '09:31 PM';
var curr_time = getval();
if (curr_time > startTime && curr_time < endTime) {
alert("No")
} else {
alert('Yes');
}
function getval() {
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10) minutes = "0" + minutes;
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
var current_time = hours + ":" + minutes + " " + suffix;
return current_time;
}
但它总是只进入Yes条件。
有人可以帮我解决这个问题吗?
这是我的jsfiddle
答案 0 :(得分:4)
尝试此代码..此代码将12小时时间转换为24小时时间。
var startTime = '12:27 PM';
var endTime = '12:36 PM';
var curr_time = getval();
if (get24Hr(curr_time) > get24Hr(startTime) && get24Hr(curr_time) < get24Hr(endTime)) {
//in between these two times
alert("Yes")
} else {
alert('No');
}
function get24Hr(time){
var hours = Number(time.match(/^(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var minutes = Number(time.match(/:(\d+)/)[1]);
hours = hours*100+minutes;
console.log(time +" - "+hours);
return hours;
}
function getval() {
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10) minutes = "0" + minutes;
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
var current_time = hours + ":" + minutes + " " + suffix;
return current_time;
}
答案 1 :(得分:0)
所以我添加了两个函数,第一个将正常时间转换为军事时间:
function makeMilitary(string) {
if (string.substr(-2) === "PM" && string.substr(0, 2) < 12)
{
var hour = parseInt(string.substr(0, 2));
string = hour + 12 + string.substr(2);
}
else if (string.substr(-2) === "AM" && string.substr(0, 2) == 12)
{
string = "00" + string.substr(2);
}
return string;
}
第二个使用第一个将开始,结束和当前转换为军事时间,然后比较它们:
function compare(start, end, current) {
start = makeMilitary(start);
end = makeMilitary(end);
current = makeMilitary(current);
if (start < end) // both times are in the same day
{
return current > start && current < end ? true : false;
}
else // the end time is on the day after the start time
{
return current > start || current < end ? true : false;
}
}
它甚至处理一个开始时间是一天结束而结束时间是下一个开始的情况。
这是JSFiddle
答案 2 :(得分:0)
您应该为变量current_time,startTime和endTime使用整数值。也可以在if语句中使用OR代替AND。