NodeJS replied that the timezone of MySQL is different when I get directly from MySQL

When I query MySQL directly, I return the date in UTC (I set UTC on the MySQL server), but with NodeJS I get the data in the local time zone of UTC + 2, why? How to install NodeJS to get UTC?

enter image description hereenter image description here

+9
timezone mysql
source share
6 answers

I added timezone in index.js when initializing mysql connection

var db_config = { host : 'localhost', user : 'xxx', password : '', database : 'xxx', timezone: 'utc' //<-here this line was missing }; 
+44
source share

Although this is an old question, I had a similar problem and adding timezone: 'utc' configuration did not solve the problem (it gets worse).

The solution that I eventually used is to add config dateStrings: true , so that I have a raw string date, and the mysql module does not do the conversion to javascript date itself.

Then I use moment.utc (thedatestring) to get a suitable javascript object (in the database I save all dates as UTC in DATETIME columns, regardless of the host configuration). Using Moment.js .

+6
source share

You can also set the dateStrings property to DATETIME.

dateStrings: date date types (TIMESTAMP, DATETIME, DATE) that must be returned as strings and then inflated into JavaScript Date objects. (Default: false)

Contact: https://github.com/mysqljs/mysql#connection-options

+2
source share

Try setting the time zone value to "UTC + 0", which worked for me.

+2
source share

after I ran into this problem over and over again, I found the solution I wanted.

My nodeJS application data from mySQL data through Sequelize ORM.

Make sure the time zone is the same everywhere.

config.js :

 const timezone = 'UTC' process.env.TZ = timezone 

sequelize_config.js :

 const sequelize = new Sequelize(database, user, password, options: { host, dialect: 'mysql', port, dialectOptions: { /* useUTC: true, **deprecated** */ timezone: 'utc' }, } } 

Hope this saves someone from getting into this cycle ... :)

+1
source share

An old question, but it can be solved by setting the TZ environment variable to 'UTC + 0'. There are several ways to achieve this, some of them:

  • In Bash:
    • $ TZ='UTC+0' node index.js
  • Inside the code:
    • process.env.TZ = "UTC+0"
  • In Visual Code launch.json configuration launch.json . For example:
  { "type": "node", "request": "launch", "name": "Launch Program", "program": "${fileDirname}/${fileBasename}", "env": {"TZ": "UTC+0"} // <-- ADD THIS } 
0
source share

All Articles