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