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?
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?
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
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");
}
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.