NodeJS responded MySQL timezone is different when I fetch directly from MySQL
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.
I know this question is already answered, and old, but if you are using mysql2 library and having problems setting the timezone to UTC, you can do it using "Z" timezone. Z stands for Zulu, explanation from here
const mysql = require('mysql2')
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'test',
password: 'mypass',
timezone: 'Z',
})
Setting this timezone configuration means that every Date (Javascript Date object) will be translated TO utc when sent to database and FROM utc when it comes from the database. Here is the implementation, from mysql2 GitHub repository.
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
};
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... :)