I have a simple node.js server that accepts requests & queries a database. When I try to query all balances using the following function
const Pool = require('pg').Pool;
const pool = new Pool({
user: 'myUsername',
host: 'localhost',
database: 'myDatabase',
password: 'myPassword',
port: 5432,
});
const getBalances = (request, response) => {
pool.query('SELECT * FROM balances', (error, results) => {
if (error) {
throw error
}
response.status(200).json(results.rows)
})
};
I get the following result (ignore the balances, the relevant part dates)
[{"balance":400,"last_received":"2020-06-20T22:00:00.000Z"},
{"balance":200,"last_received":"2020-06-20T22:00:00.000Z"},
{"balance":200,"last_received":"2020-06-20T22:00:00.000Z"},
{"balance":400,"last_received":"2020-06-20T22:00:00.000Z"}]
This is odd, as the last_received should point to today's date. When I check this using the PostgreSQL CLI, I get the following result using the same query as in the node.js code:
balance | last_received
--------+--------------
400 | 2020-06-21
200 | 2020-06-21
200 | 2020-06-21
400 | 2020-06-21
The Date is not the same, and it doesn't return the time as when I query using node.js either. The date datatype I used for creating the table is the standard DATE datatype from PostgreSQL. Why is this and how do I resolve this?
What I've tried:
I've tried re-querying and restarting both multiple times to be sure it's not some sort of timing error, but each time the same result and I've queried show timezone
and gotten the same result on both ends.
Additionally, when querying select now()
I get the correct and same date on both views, yet when I query select CURRENT_DATE
they are different by a day, indicating the problem lies somewhere with the CURRENT_DATE keyword.
node-postgres converts Date
types to Datetime
in the local timezone, so it's converting to your server/node timezone.
So, either adjust the dates after fetching them, adjust your server/node timezone, or override the type parser.