Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

enter image description hereenter image description here

like image 491
János Avatar asked May 09 '14 17:05

János


People also ask

How do I set MySQL server time zone?

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).

Does MySQL use UTC?

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.

Does MySQL TIMESTAMP store timezone?

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.


3 Answers

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
};
like image 153
János Avatar answered Sep 23 '22 17:09

János


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.

like image 45
Azias Avatar answered Sep 22 '22 17:09

Azias


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.

like image 28
Marco Blos Avatar answered Sep 26 '22 17:09

Marco Blos