comparing two same date return isEqual to false
Hi,
i'm trying to compare two iso dates to know if my range is on full day. to do this I have the following function
export const isFullDay= (from: string, to: string) => {
return isEqual(startOfDay(parseISO(from)), parseISO(from)) && isEqual(endOfDay(parseISO(to)), parseISO(to))
}
the first isEqual return true but the second return false for this case :
=> endOfday(date) / date :
- Mon Jun 14 2021 23:59:59 GMT+0200 (heure d’été d’Europe centrale)
- Mon Jun 14 2021 23:59:59 GMT+0200 (heure d’été d’Europe centrale)
=> isEqual : false
It's hard to confirm without seeing the actual string inputs used in your example, but I suspect you might not be defining milliseconds explicitly and that's where the date comparison fails.
The time portion of endOfDay's result is 23:59:59.999, not 23:59:59.000. The native Date's toString method doesn't display milliseconds, which would give the impression that both dates are equal while they are not.
const date = new Date(2021, 5, 14, 23, 59, 59, 999); // 999 ms
const end = endOfDay(date)
console.log(isEqual(date, end)); // true
console.log(date.getTime()) // 1623729599999
console.log(end.getTime()) // 1623729599999
const date = new Date(2021, 5, 14, 23, 59, 59); // 0 ms
const end = endOfDay(date)
console.log(isEqual(date, end)); // false
console.log(date.getTime()) // 1623729599000
console.log(end.getTime()) // 1623729599999
Hope this helps!
It's hard to confirm without seeing the actual string inputs used in your example, but I suspect you might not be defining milliseconds explicitly and that's where the date comparison fails.
This is exactly the issue I was just trying to resolve. Thanks for the tip!
I wonder if it would be best to have a parameter in isEqual that sets the precision, so we could for example ignore milliseconds.
I wonder if it would be best to have a parameter in
isEqualthat sets the precision, so we could for example ignore milliseconds.
For example, day.js has this https://day.js.org/docs/en/query/is-same
@marko-hologram precision is a good idea. I'll add it. Thank you!
@marko-hologram precision is a good idea. I'll add it. Thank you!
Wow didn't expect such a quick reaction. Will you add that precision argument for isEqual only or for isBefore/isAfter as well? I think it would make sense for all these comparison functions because sometimes you just want to compare days or months and not care about millisecond precision.
isSameDay might work