0

I have Datetimes formated as "16 Apr 2020 02:07 PM CST" and I need to compare it to another datetime just like that to know which date came first.

What I tried to do until now was:

var firstDate = "16 Apr 2020 02:07 PM CST";
var secondDate = "23 Apr 2020 06:07 AM CST";

var diff = Math.abs(firstDate - secondDate);

That or I tried to check if one was greater than the other and got similar results.

Mat Mol
  • 73
  • 1
  • 1
  • 9
  • 1
    Use the answers to [Converting a string to a date in JavaScript](https://stackoverflow.com/questions/5619202/converting-string-to-date-in-js) to get your strings to date. – Heretic Monkey Apr 17 '20 at 18:47

1 Answers1

1

You should check time in milliseconds (timestamp) to compare dates:

var firstDate = new Date("16 Apr 2020 02:07 PM CST");
var secondDate = new Date("23 Apr 2020 06:07 AM CST");

if (firstDate.getTime() < secondDate.getTime()) {
  console.log('First Date came first');
} else {
  console.log('Second Date came first');
}