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>
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!