Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare time with AM PM in JavaScript

Tags:

javascript

I have two strings as follows:

var a = "11/24/2014 3:10 PM" var b = "11/23/2014 7:45 AM"

How can I compare them with JavaScript, so that I could show that the time for var b happens before var a?

like image 982
photonacl Avatar asked Dec 04 '25 12:12

photonacl


2 Answers

DEMO

Convert the date stamp into UNIX time codes and then compare the two

var a = "11/24/2014 3:10 PM";
var b = "11/23/2014 7:45 AM";

var aDate = new Date(a).getTime();
var bDate = new Date(b).getTime();

if(aDate < bDate){
    console.log('a happened before b');
}else if (aDate > bDate){
    console.log('a happend after b');
}else{
    console.log('a and b happened at the same time')
}
like image 51
haxxxton Avatar answered Dec 07 '25 01:12

haxxxton


You need to Parse dates to DateType take a look at following snippet

var a = "11/24/2014 3:10 PM" 
b = "11/23/2014 7:45 AM"
var aDate= new Date(Date.parse(a));
var bDate = new Date(Date.parse(b));

if (aDate> bDate ){
  alert(aDate)   
}else{
  alert(bDate);       
}
like image 25
Dnyanesh Avatar answered Dec 07 '25 03:12

Dnyanesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!