0

I'm trying to compare time a and time b. My JavaScript looks like this

    var a ="02/08/2016 9:00 AM";
    var b ="02/08/2016 11:20 PM";

    if (b<a || b==a){
       alert("End time is before or same as Start time.");
    }
    else{
       alert("Start time is before End time.")
}

After I run this code, it tells me that "The end time is before or same as the start time"? I thought with the values of a and b that I set, it should the other way around?

photonacl
  • 35
  • 1
  • 7

1 Answers1

2

You have to turn them into dates and compare the time. getTime is not needed if you are sure you are going to compare using < <= >= > operators but won't work with equality == === != !== operators so I think it's best to just go for getTime

This is a simple and quick way to do a comparison but i suggest you to check how dates work (also what's the best format for dates)

var a =new Date("02/08/2016 9:00 AM");
var b =new Date("02/08/2016 11:20 PM");

if (b.getTime()<=a.getTime()){
   alert("End time is before or same as Start time.");
}
else{
   alert("Start time is before End time.")
}
valepu
  • 3,136
  • 7
  • 36
  • 67
  • 1
    Or you could use `<=`?? – Liam Feb 15 '16 at 15:46
  • It's a bad idea to use non-standard mm/dd/yyyy format (or is it dd/mm/yyyy?) because all engines might not recognize it. – JJJ Feb 15 '16 at 15:46
  • @Liam yes, right, i just got the question's code and didn't think about it. Editing – valepu Feb 15 '16 at 15:48
  • @valepu Hi Valepu, your code works great. But what do you mean by suggesting me to check how dates work. Do you mean the code you have provided has border cases where the code perhaps won't work? Just wanna make sure. Thanks – photonacl Feb 15 '16 at 16:03
  • No it's just for your general knowledge. You should check the question yours was marked as duplicate and also https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date – valepu Feb 15 '16 at 16:12