I have the following string value of a date, Sun Apr 07 2019 00:00:00 GMT-0300
, and I need to compare with the following date form
Build a date from the strings and compare the days (ie number of seconds since epoch / number of seconds in a day):
const sameDay = (dateString1, dateString2) => {
let time1 = (new Date(dateString1)).getTime();
let time2 = (new Date(dateString2)).getTime();
return Math.floor(Math.abs((time1-time2))/(1000*60*60*24))==0;
}
console.log(
sameDay('Sun Apr 07 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)','2019-04-08T03:00:00.000Z'),
sameDay('Sun Apr 07 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)','2019-04-13T03:00:00.000Z'),
);
Sun Apr 07 2019 00:00:00 GMT-0300
2019-04-08T03:00:00.000Z
note that both are the same day
No, they are not.
You can convert them both to ISO string and just compare their date parts as strings (if I understood the question correctly, you want to compare date only, without time):
function isSameDate(date1, date2) {
const [d1, ] = (new Date(date1)).toISOString().split('T');
const [d2, ] = (new Date(date2)).toISOString().split('T');
return d1 === d2;
}
Convert all the values to Date
objects and compare those. Use a framework/library to do it, because parsing strings to dates manually has lots of places where it can go wrong.
Currently you are comparing the literal String
s. Because neither "2019-04-08T03:00:00.000Z"
, nor "2019-04-13T03:00:00.000Z"
match "Sun Apr 07 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)"
, your second if
statement fails.