Home > Database > Mysql Tutorial > body text

Why Does NodeJS Return MySQL Dates in UTC 2 While Direct MySQL Fetch Returns UTC?

Patricia Arquette
Release: 2024-10-25 05:33:29
Original
308 people have browsed it

Why Does NodeJS Return MySQL Dates in UTC 2 While Direct MySQL Fetch Returns UTC?

NodeJS Returns Different MySQL Timezone Than Direct MySQL Fetch

Question:

When making a direct request to MySQL, you receive dates in UTC, which is the timezone configured on the server. However, when fetching data through NodeJS, you consistently encounter a UTC 2 timezone offset. Why is this occurring and how can you rectify this issue to obtain UTC dates?

Answer:

The discrepancy in timezone handling stems from a missing configuration in your NodeJS environment. Specifically, you need to set the timezone to 'utc' when initializing the MySQL connection.

To resolve this issue, add the following line to your NodeJS code where you establish the MySQL connection:

db_config.timezone = 'utc';
Copy after login

For instance, if your code is defined in a file named index.js, you would have the following configuration:

<code class="javascript">var db_config = {
  host: 'localhost',
  user: 'xxx',
  password: '',
  database: 'xxx',
  timezone: 'utc'
};</code>
Copy after login

Once this configuration is in place, NodeJS will properly interpret and display dates in UTC, aligning with the values you obtain when fetching data directly from the MySQL server. This ensures consistency and accuracy in handling datetime fields across different environments.

The above is the detailed content of Why Does NodeJS Return MySQL Dates in UTC 2 While Direct MySQL Fetch Returns UTC?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!