I am using Node.js with pg to query a Postgres database. I am trying to execute the following query:
SELECT COUNT(*) FROM table_name WHERE date_time_added::date = some_date;
some_date is the date I pass from Node.js.
I have no problems with this most of the time, as both date/time strings are in the same format. However, issues arise when Timezones are introduced. As I am located in the UK, we use British Summer Time (GMT+1) for some parts of the year.
When I cast date_time_added from it's stored type (timestamp with timezone) to date, the time defaults to midnight. The issue with this is that during BST, the timestamp is cast to one day earlier, and the time set to 23:00 instead of 00:00, as shown below:
{ date_time_added: 2020-09-28T23:00:00.000Z }
This wouldn't be a problem if JavaScript had the same behaviour, however if I try the following:
const date1 = new Date(2020, 8, 29, 10, 47, 54);
console.log(date1.toString());
date1.setHours(0);
date1.setMinutes(0);
date1.setSeconds(0);
date1.setMilliseconds(0);
console.log(date1.toString());
The following output is produced:
"Tue Sep 29 2020 10:47:54 GMT+0100 (British Summer Time)"
"Tue Sep 29 2020 00:00:00 GMT+0100 (British Summer Time)"
The time is set to midnight rather than 23:00 the day before. This is a problem for me as this means the dates don't match, and therefore the row is not returned in the database query.
Does anyone know how I can get the same behaviour for both dates (JS and Postgres)? It would be good to be able to initialise a new Date Object with the time defaulting in the same way as Postgres does when I cast to date, however I am not sure if this is possible.
now()function in Postgres - then it is better to compare the timestamps inside your SQL queries.