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?
Option 2: Edit the MySQL Configuration File Scroll down to the [mysqld] section, and find the default-time-zone = "+00:00" line. Change the +00:00 value to the GMT value for the time zone you want. Save the file and exit. In the example below we set the MySQL Server time zone to +08:00 (GMT +8).
Internally, a MySQL timestamp column is stored as UTC. But, when you select a date, MySQL automatically converts the timestamp column to the current session's time zone. MySQL converts TIMESTAMP values from the current time zone to UTC for storage.
MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME .) By default, the current time zone for each connection is the server's time.
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
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With