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

Safari\'s \'Invalid Date\' Issue: How to Handle Date Parsing Inconsistencies

Linda Hamilton
Release: 2024-10-21 17:37:02
Original
874 people have browsed it

Safari's

Invalid Date Issue in Safari:

In web development, handling dates can sometimes pose challenges across different browsers. A browser-specific parsing issue arises when creating a new Date object using certain input formats, as illustrated in the example below:

alert(new Date('2010-11-29'));
Copy after login

While browsers like Chrome and Firefox handle this format without issue, Safari encounters the error "invalid date." The reason for this discrepancy lies in the way Safari interprets the input string.

To resolve this issue, a regular expression can be employed to convert the string into a format that Safari recognizes. Here's a simple one-liner solution:

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

In this code, the regular expression /-/g replaces all hyphen characters (-) with forward slashes (/), resulting in a string that conforms to Safari's expected date format. This substitution allowsSafari to successfully parse the date and display a valid result.

The above is the detailed content of Safari\'s \'Invalid Date\' Issue: How to Handle Date Parsing Inconsistencies. 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!