Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

string - How to compare time in javascript?

I have two time in the format "HH:MM" i want to compare them i have the following code to get the time of now in my format:

current_time = new Date();
hour = current_time.getHours();
minute = current_time.getMinutes();
if(hour<10){hour='0'+hour} if(minute<10){minute='0'+minute}
my_time = hour+':'+minute;

And this code is to get the time after subtracting the GMT difference :

d = new Date()
var n = d.getTimezoneOffset();
var n1 = Math.abs(n);
var difference = (n1/60); 
my_time = my_time - (0+difference);

Now the value of my_time should be compared with the value of match_time:

match_time = 10:00;//for example
if(my_time > match_time)
{
  alert('yes');
}
else
{
  alert('No');
}

how can I compare those values as time when they are a string ???

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

use Date objects. Date.setHours() allows you to specify hour, minutes, seconds

var currentD = new Date();
var startHappyHourD = new Date();
startHappyHourD.setHours(17,30,0); // 5.30 pm
var endHappyHourD = new Date();
endHappyHourD.setHours(18,30,0); // 6.30 pm

console.log("happy hour?")
if(currentD >= startHappyHourD && currentD < endHappyHourD ){
    console.log("yes!");
}else{
    console.log("no, sorry! between 5.30pm and 6.30pm");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...