Time/Date Diff is Inaccurate.
See original GitHub issueSo we are using ISO Strings to log timestamps in our DB for various different things, and one thing we need to do is take the local server date/time, and then a date/time from our database and differentiate it and get the time between them.
So we did something like this;
const getTimeRemaining = enddate => {
const end = DateTime.fromISO(enddate);
const start = DateTime.local();
const finalDate = end.diff(start, ['days', 'hours']).toObject();
if (finalDate.days !== 0) {
return `${finalDate.days} Days Left`;
}
return `${finalDate.hours} Hours Left`;
};
Now this is functional, but the time returned will always be 1 hour ahead.
For example, our server time is; Dec 29 03:55:23
The end date in our database is; 2018-12-29T03:50:00.000Z
.
So this should now be returning a negative since the duration has gone past the end date, but for some odd reason we instead get this 0.9165527777777778 Hours Left
, so it’s adding an additional hour for no reason. (That I can see at least).
If we swap the diff around so it’s const finalDate = start.diff(end, ['days', 'hours']).toObject();
This fixes the issue, but then obviously all values are negative. I can just strip the negative value from the strings I suppose, but this doesn’t feel like the best way I should be doing things.
Hopefully you guys can let me know what is going wrong here.
Issue Analytics
- State:
- Created 5 years ago
- Comments:7 (4 by maintainers)
Hi,
If I were guessing, I would say you are somewhere just east of GMT - perhaps Amsterdam, Berlin, Paris or Lagos, where there is a 1 hour offset from UTC right now 😃. The problem you have here is that your database has a UTC date (as designated by the
Z
at the end of the value), but you are comparing it to a local date. Having switched my computer to Berlin time for fun, I can break your problem down a bit.Your end date is 2018-12-29T03:50:00.000Z, but
DateTime.fromISO()
will change dates it parses from UTC to local by default. Thus, upon parse you get this:If that date really is in UTC, then once converted to local time, it is in fact .91 hours AHEAD of your start time, which is presumably also in local time - as you are using
.local()
to generate it.Perhaps working as intended for the package but definitely not intended in my use-case. I’m currently testing storing the values with the offset like so;
2018-12-30T16:00:27.425+01:00
Hopefully this fixes it.