Reputation: 908
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 format 2019-04-08T03:00:00.000Z
, note that both are the same day, I need to compare them and return a true as being equal days,
but I do not know how to do this using javascript, any help?
I tried to do something like this but it does not return me true:
if (input) {
//input.value = "Sun Apr 07 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)"
var situation = angular.isArray(item.situation) ? item.situation : [item.situation];
// situation =
//[
// 0: "2019-04-08T03:00:00.000Z"
// 1: "2019-04-13T03:00:00.000Z"
//]
if (!angular.isArray(input.value)) {
condition = situation.indexOf(input.value) >= 0;
} else if (angular.isArray(input.value)) {
condition = $window._.intersection(situation, input.value).length > 0;
}
}
if (condition) {
break;
}
//input.value = "Sun Apr 07 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)"
situation =
[
0: "2019-04-08T03:00:00.000Z"
1: "2019-04-13T03:00:00.000Z"
]
Upvotes: 1
Views: 466
Reputation: 10076
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;
}
Upvotes: 3
Reputation: 4147
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.
Upvotes: 0
Reputation: 18493
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'),
);
Upvotes: -1