Reputation: 1397
I have been using the date-fns function "isSameDay" to test if two actions take place on the same day. The function is given two standard javascript date objects. We recently found a bug where the isSameDay function returns false if the two dates are the same, but one of the two date objects has a time after 7pm.
const sameDay = isSameDay(date1, date2);
To make it confusing, the function returns true when run locally, but false on the server. I believe that this has something to do with the time zone difference between me locally and the server.
My expectation was that the date-fns functions would not be affected by being run in a different time zone as the date-time objects it is being given are all UTC.
When I first started looking at this, I took the two date-time objects and ran getFullYear, getMonth, and getDate and then compared those two items and got a false again when one date-time object was after 7pm - same as with the date-fns function.
There are options in the isSameDay function that may be able to handle the issue at hand, but the documentation doesn't explain it well enough.
What I have had to do as a work around is to create two strings for the two dates in question after forcing those dates to be central time zone and then compare the strings.
Can anyone explain if/how options can be used so that the isSameDay function works correctly?
Upvotes: 0
Views: 257
Reputation: 2914
Not an answer, but too long for a comment.
This is how I use it. Server is in UTC, but our services need to consider another timezone:
// [email protected]
import { log } from 'firebase-functions/logger';
import { isSameDay } from 'date-fns';
import { tz } from '@date-fns/tz';
import { es as dateLocale } from 'date-fns/locale/es';
import { format } from 'date-fns';
const TIME_ZONE = 'Europe/Madrid';
function _needsRestart(settings) {
// restart counters if we've changed to next day
const date = settings.balanceUpdatedAt.toDate();
const now = new Date();
const needsRestart = !isSameDay(date, now, { in: tz(TIME_ZONE) });
log(`Restart? ${needsRestart}. date: ${formatDate(date, 'Pp')} -> now: ${formatDate(now, 'Pp')}, (${TIME_ZONE})`);
return needsRestart;
}
// helper:
function formatDate(date, format = 'P') {
return format(date.toDate ? date.toDate() : date, format, { locale: dateLocale, in: tz(TIME_ZONE) });
}
Upvotes: 0
Reputation: 561
Have you tried converting the dates to UTC before comparing? At least this would remove the timezone problem
Upvotes: 0