NodeJS responded MySQL timezone is different when I fetch directly from MySQL

前端 未结 6 1875
深忆病人
深忆病人 2020-12-03 05:10

When I request MySQL directly, I get back date in UTC (I set UTC in MySQL server), but with NodeJS I get UTC+2 local time zone data, why? How can I set NodeJS to get UTC?

相关标签:
6条回答
  • 2020-12-03 05:58

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

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

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

    0 讨论(0)
  • 2020-12-03 05:59

    Try setting the timezone value to "UTC+0", that worked for me.

    0 讨论(0)
  • I have 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
    };
    
    0 讨论(0)
  • 2020-12-03 06:01

    Old question, but it can be resolved setting the TZ environment variable to 'UTC+0'. There are several ways to achieve that, a few of them are:

    • In bash:
      • $ TZ='UTC+0' node index.js
    • Inside the code:
      • process.env.TZ = "UTC+0"
    • In Visual Code alter the launch.json configuration file. E.g:
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${fileDirname}/${fileBasename}",
            "env": {"TZ": "UTC+0"}  // <-- ADD THIS
        }
    
    0 讨论(0)
  • 2020-12-03 06:05

    You can also set the dateStrings property to DATETIME.

    dateStrings: Force date types (TIMESTAMP, DATETIME, DATE) to be returned as strings rather then inflated into JavaScript Date objects. (Default: false)

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

    0 讨论(0)
  • 2020-12-03 06:08

    after falling to that problem again and again i've found the desired solution.

    My nodeJS app fetching data from mySQL db via Sequelize ORM.

    Make sure the timezone 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 it will save someone's time from falling to this loop... :)

    0 讨论(0)
提交回复
热议问题