1

I have two date strings with different formats:

var date1 = "20/09/2016";//DD/MM/YYYY
var date2 = "Sep 5, 2018 12:00:00 AM"; // MMM DD, YYYY hh:mm:ss AM

How can I convert the two string to date just using DD & MM & YYYY and compare them?

David Walschots
  • 12,279
  • 5
  • 36
  • 59
  • First, [convert them to dates](https://stackoverflow.com/questions/5619202/converting-string-to-date-in-js), then [Compare two dates with JavaScript](https://stackoverflow.com/q/492994) – Heretic Monkey Sep 19 '18 at 17:37
  • Possible duplicate of [Javascript - Convert string to date and compare dates](https://stackoverflow.com/questions/31256564/javascript-convert-string-to-date-and-compare-dates) – Heretic Monkey Sep 19 '18 at 17:39
  • no the question is not duplicated. – Abdelmajid Bahmed Sep 19 '18 at 17:46

2 Answers2

0

In order to compare both dates, you have to convert it to a Date type first.

for DD/MM/YYYY I changed the order of date and month so it can be processed by new Date() and the other date format could be converted directly.

After that you just get the time and compare it however you want. Also, you can use methods like getYear, getMonth or getDate if you only want to compare those fields

Date information

var dateParts = "20/09/2016".split("/");

var date1 = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
var date2 = new Date("Sep 5, 2018 12:00:00 AM"); // MMM DD, YYYY hh:mm:ss AM

if (date1.getTime() > date2.getTime()){
  console.log("date1 is higher");
}else {
  console.log("date1 is lower");
}
Pietro Nadalini
  • 1,722
  • 3
  • 13
  • 32
  • 1
    Re "*… you have to convert it to a Date type first.*" Not necessarily. If both are formatted as YYY-MM-DD they can be compared as strings, or remove the dash and compare them as numbers. ;-) – RobG Sep 19 '18 at 20:21
0

To compare them, you can construct the Date object with the following ISO format in UTC, and then use the getTime method:

var newDate1 = new Date('2016-09-20Z');
var newDate2 = new Date('2018-08-05T12:00:00Z');
var equalDates = newDate2.getTime()===newDate1.getTime();

The Z in the end indicates it should be parsed as UTC.

If you can't directly construct them like this you should parse them like you would any other string. Here's how you can parse the first string, for example:

var date1 = "20/09/2016";
var dateArray=date1.split('/');
var newDate1 = new Date(dateArray[2], dateArray[1] - 1, dateArray[0]); //JavaScript counts months from 0

The moment.js library could be useful for you too.

JaimeGo
  • 39
  • 3
  • No need to parse the second string in this case. The Date constructor will accept it – JaimeGo Sep 19 '18 at 18:26
  • "*The Z in the end indicates it should be parsed as UTC*". Not for a date, where the Z creates a non-standard string, so the parsing is implementation dependent and creates an invalid date in at least one browser in use. – RobG Sep 19 '18 at 20:23