Can anyone tell me how to that? I would like to compare 2 times and find out which one is greater? like 12:30 pm and 5:30 pm
Asked
Active
Viewed 7,050 times
2
-
1check it here: http://stackoverflow.com/questions/6212305/how-can-i-compare-two-time-strings-in-the-format-hhmmss – herkulano Sep 24 '11 at 13:19
5 Answers
1
Use Date().parse()
Date.parse('24/09/2011 15:21:41')

genesis
- 50,477
- 20
- 96
- 125
-
@sam `Date.parse()` should work with a lot of different formats. Have you actually tried this yet? – Bojangles Sep 24 '11 at 13:27
1
If the input is always similar as mentioned at the question:
var time1 = "12:30 pm";
var time2 = "5:30pm";
var time1_higher_than_time2 = compareTime(time1, time2);
if(time1_higher_than_time2) alert("Time1 is higher than time 2");
else alert("Time1 is not higher than time 2. "); /* Time1 <= time2*/
/*Illustrative code. Returns true if time1 is greater than time2*/
function compareTime(time1, time2){
var re = /^([012]?\d):([0-6]?\d)\s*(a|p)m$/i;
time1 = time1.match(re);
time2 = time2.match(re);
if(time1 && time2){
var is_pm1 = /p/i.test(time1[3]) ? 12 : 0;
var hour1 = (time1[1]*1 + is_pm1) % 12;
var is_pm2 = /p/i.test(time2[3]) ? 12 : 0;
var hour2 = (time2[1]*1 + is_pm2) % 12;
if(hour1 != hour2) return hour1 > hour2;
var minute1 = time1[2]*1;
var minute2 = time2[2]*1;
return minute1 > minute2;
}
}

Rob W
- 341,306
- 83
- 791
- 678
1
Turn the times into javascript dates
, call getTime()
on the dates to return the number of milliseconds since midnight Jan 1, 1970.
Compare the getTime()
returned values on each date to determine which is greater.
For 12 Hour format the code below will work.
var date1 = new Date('Sat Sep 24 2011 12:30:00 PM').getTime(); //12:30 pm
var date2 = new Date('Sat Sep 24 2011 5:30:00 PM').getTime(); //5:30 pm
if(date1 > date2) {
alert('date1 is greater');
} else if(date2 > date1) {
alert('date2 is greater');
} else {
alert('dates are equal');
}

Allen Tellez
- 1,198
- 1
- 10
- 14
0
Check out the below link-
http://www.dotnetspider.com/forum/162449-Time-Comparison-Javascript.aspx
You can test out your javascript online here -
http://www.w3schools.com/js/tryit.asp?filename=tryjs_events
<html>
<head>
<script type="text/javascript">
var start = "01:00 PM";
var end = "11:00 AM";
var dtStart = new Date("1/1/2007 " + start);
var dtEnd = new Date("1/1/2007 " + end);
var difference_in_milliseconds = dtEnd - dtStart;
if (difference_in_milliseconds < 0)
{
alert("End date is before start date!");
}
</script>
</head>
<body>
</body>
</html>

Philippe Plantier
- 7,964
- 3
- 27
- 40