Home  >  Article  >  Web Front-end  >  Why does `new Date()` behave differently in Chrome and Firefox when converting UTC time strings?

Why does `new Date()` behave differently in Chrome and Firefox when converting UTC time strings?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 02:51:02545browse

Why does `new Date()` behave differently in Chrome and Firefox when converting UTC time strings?

Understanding the Discrepancy in new Date() Behavior between Chrome and Firefox

When converting a date string to a Date object using new Date(), a subtle difference arises between Chrome and Firefox. This behavior can be confusing, especially when working with UTC time strings.

The code provided in the question, var date = new Date('2013-02-27T17:00:00');, creates a Date object from a date string in UTC format. However, the result differs between the two browsers:

  • Firefox: Returns a date one day behind the expected UTC time.
  • Chrome: Returns the correct UTC time.

The Cause of the Discrepancy

The difference stems from the interpretation of the date string. Firefox interprets the string as a local time in the browser's timezone, while Chrome interprets it as UTC. As a result, Firefox adds the browser's timezone offset to the date, causing it to be displayed one day behind UTC.

The Solution

To resolve this discrepancy and obtain the correct UTC time in both browsers, it is essential to adhere to the proper format for UTC date strings. The correct format is:

YYYY-MM-DDTHH:mm:ssZ

where:

  • YYYY-MM-DD represents the year, month, and day.
  • HH:mm:ss represents the hour, minute, and second.
  • Z represents the Zulu Time indicator.

By adding the "Z" indicator to the end of the date string, browsers will correctly interpret it as UTC time.

Updated Code:

<code class="javascript">var date = new Date('2013-02-27T17:00:00Z'); // Appends 'Z' to indicate UTC
alert(date);</code>

This updated code will now produce the same correct UTC date object in both Firefox and Chrome.

The above is the detailed content of Why does `new Date()` behave differently in Chrome and Firefox when converting UTC time strings?. 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