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

How to Resolve \'Invalid Date\' Error When Converting MM-DD-YYYY String to Date Object in Safari?

Susan Sarandon
Release: 2024-10-21 17:53:11
Original
700 people have browsed it

How to Resolve

"Safari Date Conundrum: Invalid Date Blues and a One-Liner Fix"

When attempting to create a new Date object in Safari using a string in MM-DD-YYYY format, users may encounter an "invalid date" error. While other browsers like Chrome and Firefox handle this format effortlessly, Safari poses a challenge.

Upon further investigation, it was discovered that Safari's strict adherence to the ISO 8601 date format is the root of the issue. This format requires the date to be in YYYY-MM-DD format, which is not compatible with the MM-DD-YYYY string being used.

Attempts to resolve the issue by manually parsing the string using different separators (e.g., //, -/) proved futile. Safari remained adamant in its insistence on the ISO 8601 format.

A One-Liner Solution

For those seeking a quick and effective fix without resorting to external libraries, a simple one-liner can bypass Safari's date parsing limitations:

console.log (new Date('2011-04-12'.replace(/-/g, "/")));
Copy after login

In this line, the replace() method is utilized to convert the MM-DD-YYYY string to the YYYY-MM-DD format that Safari recognizes. By replacing all hyphens (-) with forward slashes (/), the date string becomes compliant with the ISO 8601 standard.

This concise solution allows users to create new Date objects using a non-standard format while maintaining compatibility with Safari.

The above is the detailed content of How to Resolve \'Invalid Date\' Error When Converting MM-DD-YYYY String to Date Object in Safari?. For more information, please follow other related articles on the PHP Chinese website!

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