Home > Web Front-end > JS Tutorial > body text

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

Susan Sarandon
Release: 2024-10-27 01:49:30
Original
243 people have browsed it

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>
Copy after login

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)
Copy after login

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)
Copy after login
Copy after login

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>
Copy after login

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)
Copy after login
Copy after login

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!

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!