Library is converting my datetime string to UTC
See original GitHub issueI’m working on a DB that was converted from MySQL to Postgres using a migration script. While converting the database interactions from mysql
to node-postgres
, I noticed that my test SQL queries were not being stored correctly - all my datetimes that were being input as ISO-8601 formatted strings with an explicit UTC flag (“YYYY-MM-DDThh:mm:ss.sssZ”) were getting treated as though they were local timestamps and being implicitly converted to the “correct” UTC timezone.
There doesn’t appear to be any official way to override this behavior, and as such it is seriously getting in the way of my conversion. I tried changing the datetime strings to signify UTC using the timezone-offset format (“YYYY-MM-DDThh:mm:ss.sss+00:00”), but it made no difference.
Issue Analytics
- State:
- Created 5 years ago
- Comments:11 (1 by maintainers)
To summarize and hopefully clear up any confusion:
When you supply a JS
Date
object as an input value, the library converts it to a string literal that Postgres can understand. By default, this literal will be in local time, with the appropriate timezone offset, rather than UTC.This is fine for
timestamp with time zone
a.k.a.timestamptz
because you end up with the same thing stored either way (barring a rare edge case that has to do with the precision of JS’s.getTimezoneOffset()
), and parsing back to aDate
object doesn’t require any assumptions.But the
timestamp
anddate
types just ignore the offset part on input, there’s no automatic conversion to UTC first, so the value ends up being in local time. Since this is usually not what you want, you can fix it by doing:…or by calling
.toISOString()
like @tim-phillips says (just beware that this method may have issues for dates far in the past/future since the format isn’t 100% compatible with Postgres).The caveat with this is that the output parsing done by postgres-date also assumes local time for
timestamp
anddate
types, so those output parsers need to be overridden (as others have shown) if you value your sanity and want roundtrips to succeed.As for the default behaviour being changed, #783 seems to indicate that this is unlikely (it may not be worth the breaking change in any case).