Home  >  Article  >  Web Front-end  >  Why Does `new Date()` Interpret UTC Strings Differently in Chrome and Firefox?

Why Does `new Date()` Interpret UTC Strings Differently in Chrome and Firefox?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-01 07:29:30887browse

Why Does `new Date()` Interpret UTC Strings Differently in Chrome and Firefox?

Differences in new Date() Behavior Between Chrome and Firefox

When attempting to convert a date string to a Date object using the new Date() constructor, behavior can vary between different browsers. This is particularly evident when dealing with UTC (Coordinated Universal Time) date strings.

In the provided code snippet:

var date = new Date('2013-02-27T17:00:00');
alert(date);

Chrome interprets the input string as a local time, adjusting it based on the browser's time zone. In this case, it interprets the time as 12:00 AM local time on February 28th, 2013.

Firefox, on the other hand, parses the string as a UTC time and displays it accordingly. In this case, it correctly displays the time as 5:00 PM (GMT 7:00) on February 27th, 2013.

To ensure consistent behavior across browsers, it's essential to provide the date string in the correct UTC format. The standardized format for UTC is ISO 8601, which includes a "Z" suffix to indicate UTC time:

2013-02-27T17:00:00Z

By appending "Z" to the input string, you can ensure that both Chrome and Firefox will interpret the date string as a UTC time, resulting in the same output:

var date = new Date('2013-02-27T17:00:00Z');
alert(date);

Output:

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

The above is the detailed content of Why Does `new Date()` Interpret UTC Strings Differently 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