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

How to Solve NaN Error for Internet Explorer When Constructing Dates from Formatted Strings?

Mary-Kate Olsen
Release: 2024-10-20 13:33:30
Original
761 people have browsed it

How to Solve NaN Error for Internet Explorer When Constructing Dates from Formatted Strings?

Fixing NaN Issues in Date Construction for Internet Explorer

In web development, constructing dates using the JavaScript Date constructor can present challenges in certain browsers. Particularly in Internet Explorer (IE), developers may encounter issues where the result is NaN instead of a valid date object. This can occur when attempting to parse dates in formats such as "m, d, Y".

To resolve this issue and ensure consistent functionality across multiple browsers, a custom parsing approach can be employed. Leveraging the MySQL datetime or timestamp format, the following code snippet provides a universal solution:

<code class="javascript">var dateStr="2011-08-03 09:15:11"; //obtained from MySQL datetime/timestamp field
var a=dateStr.split(" ");
var d=a[0].split("-");
var t=a[1].split(":");
var date = new Date(d[0],(d[1]-1),d[2],t[0],t[1],t[2]);</code>
Copy after login

In this code, the MySQL datetime/timestamp is split into individual parts, and the Date constructor is utilized to create a valid date object. This approach ensures that dates are parsed correctly in IE, alongside Firefox and Chrome.

The above is the detailed content of How to Solve NaN Error for Internet Explorer When Constructing Dates from Formatted Strings?. 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!