Home  >  Article  >  Database  >  Why Does NodeJS Return MySQL Dates in UTC 2 While Direct MySQL Fetch Returns UTC?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 05:33:29309browse

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';

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>

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!

Statement:
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