Home  >  Article  >  Web Front-end  >  Why Does `new Date(\'YYYY-MM-DDTHH:MM:SS\')` Produce Different Results in Chrome and Firefox?

Why Does `new Date(\'YYYY-MM-DDTHH:MM:SS\')` Produce Different Results in Chrome and Firefox?

Susan Sarandon
Susan SarandonOriginal
2024-10-27 01:49:30244browse

Why Does `new Date('YYYY-MM-DDTHH:MM:SS')` Produce Different Results in Chrome and Firefox?

Cross-browser Compatibility of Date Object Creation

When parsing a date string into a Date object using JavaScript, variations arise between different browsers such as Chrome and Firefox. This discrepancy becomes evident when using the new Date() constructor to parse a date string in the format 'YYYY-MM-DDTHH:MM:SS'.

In the provided code snippet:

<code class="js">var date = new Date('2013-02-27T17:00:00');</code>

Firefox interprets the input string as a local time and adds the local time zone offset (GMT 0700). This results in a date that is one day ahead of the intended UTC time, yielding:

Wed Feb 27 2013 17:00:00 GMT+0700 (SE Asia Standard Time)

Conversely, Chrome correctly parses the string as UTC time and returns the expected result:

Thu Feb 28 2013 00:00:00 GMT+0700 (SE Asia Standard Time)

Solution

To ensure consistent behavior across browsers, append 'Z' to the date string to explicitly indicate UTC time. The correct format for UTC would be 'YYYY-MM-DDTHH:MM:SSZ'.

<code class="js">var date = new Date('2013-02-27T17:00:00Z');</code>

This modification will resolve the discrepancy and produce the same result in both Chrome and Firefox, reflecting the original UTC time:

Thu Feb 28 2013 00:00:00 GMT+0700 (SE Asia Standard Time)

The above is the detailed content of Why Does `new Date(\'YYYY-MM-DDTHH:MM:SS\')` Produce Different Results in Chrome and Firefox?. 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