Why does DATE_SUB function not work for mysql query with node js?

55 views Asked by At

I have a datetime field in a MySQL database table on Planetscale. I want to return the datetime value after some time has been subtracted from it using the DATE_SUB function. This works in the database console on Planetscale's website but is not working from my node js server request.

Server code:

const mysql = require('mysql2');  
mysql.query('SELECT DATE_SUB(log_time,INTERVAL 4 HOUR) AS time FROM time_table;',[], function(err, records){
   if (err) {
      console.log(err);
   }
   else {
      console.log(records);
   }
})

And this is my table:

CREATE TABLE time_table (
    log_time DATETIME
);

But is not subtracting the 4 hours as I am expecting and as it does on the db console on Planetscale's website. Is this an issue with Planetscale, MySQL, MySQL2, node js, or something else? Thanks.

1

There are 1 answers

0
ahiddenjem On

Seems my issue was rooted in the fact that there are different base times for the results of the query. If I were to just enter SELECT log_time AS time FROM time_table; then the PlanetScale console will return a different time than the results output by node js query result.

I needed to subtract 4 hours to get the Planetscale time into my timezone, but coincidentally the node js results were another 4 hours ahead of planetscale. Thus, when I subtracted 4 hours it appeared to me that no time was being subtracted at all. In reality I just needed to subtract 8 hours in the node query. I guess there is some automatic time zone adjustments going on that make the output that nodes gives different from PlanetScale, but I have solved my issue.