37

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 ???

Basel
  • 1,305
  • 7
  • 25
  • 34
  • Does this answer your question? [How can I compare two time strings in the format HH:MM:SS?](https://stackoverflow.com/questions/6212305/how-can-i-compare-two-time-strings-in-the-format-hhmmss) – Vega Feb 11 '23 at 18:05

7 Answers7

34

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");
}
Gabo Esquivel
  • 3,494
  • 2
  • 23
  • 18
  • I know the question asks how to compare when strings but I think this is a better solution to the overall problem. – Ola Karlsson Oct 06 '15 at 17:19
  • Hey good solution but I had a question. Do you think it would work if I set startHappyHourD to 21:00 hours and endHappyHourD to 03:00 the next day? – Zak Sep 02 '22 at 08:39
26

Assuming you are not interested in time zones and only need to compare two formatted time strings in 24h time format, you can just compare strings.

let time1 = '09:12';
let time2 = '12:22';

if (time1 > time2) {
 alert('yes')
} else {
 alert('no')
}

It works because strings in JS are compared symbol by symbol. So when compared '09:12' > '12:22' JS first checks if '0' == '1' and if false '0' > '1', and then returns result.

For comparison of strings '01' > '02', it will check if '0' == '0' then skip to next symbol in both strings and compare '1' > '2' which is false.

Strings has to be normalized to hh:mm, otherwise you will get unexpected results like:

"9:12" > "12:22" //true
  • 1
    I did not know this was possible, thank you – Amon Feb 22 '22 at 01:12
  • 2
    You are welcome. It works because strings in JS are compared symbol by symbol. So when compared '09:12' > '12:22' JS first checks if '0' == '1' and if false '0' > '1', and then returns result. For strings like '01' > '02', it will check if '0' == '0' and if true skip to next symbol in both strings, so will next compare '1' > '2' which is false. – Igor Grechishkin Sep 01 '22 at 14:59
7
Date.parse('25/09/2013 13:31') > Date.parse('25/09/2013 9:15')

EDIT:

Note that you are parsing an arbitrary date that you're not interested in, it just needs to be the same on both sides.

Arjun Sol
  • 731
  • 5
  • 18
  • 2
    Date.parse is implementation dependent and in this case, will return NaN in some browsers (e.g. Safari). The OP can compare the strings directly as strings. – RobG Jul 28 '17 at 01:53
2

If I had enough reps to vote for @Gabo Esquivel solution. For days I have searched for and tested solutions and this is the only one that worked for me.

I needed a conditional statement testing if the current time is 0830 and if so, do something. My if statement was not working so I needed other examples to work with.

//Business Hours: Saturday 8:30am-12pm; highlight Saturday table row.
function showSaturdayHours() {
    var today = new Date();
    var weekday = today.getDay();
    var saturdayOpen = new Date();
    saturdayOpen.setHours(8, 30, 0);
    var saturdayClose = new Date();
    saturdayClose.setHours(12, 0, 0);

if (weekday == 6) {
    $('#saturday-row').addClass('row-blue'); //highlight table row if current day is Saturday.
    if (today >= saturdayOpen && today < saturdayClose) {
        document.getElementById('saturday-open').innerHTML = 'Open';
    } else {
        document.getElementById('saturday-open').innerHTML = 'Closed';
    }
  }
}

Business Hour Table : JSFiddle

TMurphy
  • 63
  • 4
2

Similar to @Arjun Sol, instead of using Date.parse, you could just grab the times from the string itself, create a new Date object and do the comparison.

const time1 = '12:42';
const time2 = '18:30';

const getTime = time => new Date(2019, 9, 2, time.substring(0, 2), time.substring(3, 5), 0, 0);

const result = getTime(time1) < getTime(time2);
console.log('This should be true:', result);
Chris
  • 2,955
  • 1
  • 30
  • 43
Pearce
  • 41
  • 3
1
 if(Date.parse('01/01/2011 10:20:45') == Date.parse('01/01/2011 5:10:10')) {
  alert('same');
  }else{

  alert('different');

  }

The 1st January is an arbitrary date, doesn't mean anything.

Chris
  • 2,955
  • 1
  • 30
  • 43
saidesh kilaru
  • 740
  • 2
  • 10
  • 18
  • See [RobG's comment on the same answer above](https://stackoverflow.com/questions/19004950/how-to-compare-time-in-javascript#comment77688259_19005001) regarding the use of `Date.parse`. – Heretic Monkey May 23 '22 at 12:36
1

we can do some hack with.

var time1 = "09:30";
var time2 = "10:30";
var time1Date= new Date("01/01/2000 "+time1);
var time2Date= new Date("01/01/2000 "+time2);

if(time1Date >= time2Date ){
    console.log("time1");
}else{
    console.log("time2");
}
Ragulan
  • 1,677
  • 17
  • 24
  • See [RobG's comment on a similar answer](https://stackoverflow.com/questions/19004950/how-to-compare-time-in-javascript#comment77688259_19005001) regarding the use of `Date.parse` (which applies equally to `new Date(string)`). – Heretic Monkey May 23 '22 at 12:37