Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node's Postgres module pg returns wrong date

I have declared a date column in Postgres as date.

When I write the value with node's pg module, the Postgres Tool pgAdmin displays it correctly.

When I read the value back using pg, Instead of plain date, a date-time string comes with wrong day.

e.g.:

Date inserted:              1975-05-11
Date displayed by pgAdmin:  1975-05-11
Date returned by node's pg: 1975-05-10T23:00:00.000Z

Can I prevent node's pg to appy time-zone to date-only data? It is intended for day of birth and ihmo time-zone has no relevance here.

like image 540
Valentin H Avatar asked Jul 24 '15 10:07

Valentin H


2 Answers

EDIT Issue response from Developer on github

The node-postgres team decided long ago to convert dates and datetimes without timezones to local time when pulling them out. This is consistent with some documentation we've dug up in the past. If you root around through old issues here you'll find the discussions.

The good news is its trivially easy to over-ride this behavior and return dates however you see fit.

There's documentation on how to do this here: https://github.com/brianc/node-pg-types

There's probably even a module somewhere that will convert dates from postgres into whatever timezone you want (utc I'm guessing). And if there's not...that's a good opportunity to write one & share with everyone!

Original message Looks like this is an issue in pg-module. I'm a beginner in JS and node, so this is only my interpretation.

When dates (without time-part) are parsed, local time is assumed. pg\node_modules\pg-types\lib\textParsers.js

if(!match) {
    dateMatcher = /^(\d{1,})-(\d{2})-(\d{2})$/;
    match = dateMatcher.test(isoDate);
    if(!match) {
      return null;
    } else {
      //it is a date in YYYY-MM-DD format
      //add time portion to force js to parse as local time
      return new Date(isoDate + ' 00:00:00');

But when the JS date object is converted back to a string getTimezoneOffset is applied. pg\lib\utils.js s. function dateToString(date)

like image 170
Valentin H Avatar answered Sep 27 '22 18:09

Valentin H


Another option is change the data type of the column:

You can do this by running the command:

ALTER TABLE table_name
ALTER COLUMN column_name_1 [SET DATA] TYPE new_data_type,
ALTER COLUMN column_name_2 [SET DATA] TYPE new_data_type,
...;

as descripted here.

I'd the same issue, I changed to text.

like image 42
mdmundo Avatar answered Sep 27 '22 18:09

mdmundo