IE Date Constructor Issue: NaN vs. Functionality in Other Browsers
Within a project involving JavaScript calendar development, discrepancies emerged in date handling between Internet Explorer (IE) and browsers like Firefox and Chrome. Specifically, IE's date functions were resulting in NaN (Not a Number) values, while they functioned properly in the other browsers.
Upon investigation, it became clear that the root cause was related to the date format being used. The function in question, buildWeek(), intended to generate header dates for a calendar week based on a Monday date provided in the 'm, d, Y' format, for example, "02, 01, 2010". However, in IE, this format was not being recognized correctly, leading to the NaN issue.
To resolve this discrepancy, a different approach was adopted. Instead of relying on the given format, the date string was split into its components (date and time) using split(" "). Subsequently, the date component was further split into its constituent parts (year, month, day) using split("-"), and the time component was split into its parts (hours, minutes, seconds) using split(":").
An instance of Date was then constructed using these parsed values. This method proved to be compatible with all browsers, ensuring consistent date handling across IE, Firefox, and Chrome.
var dateStr = "2011-08-03 09:15:11"; //returned from mysql timestamp/datetime 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]);
By adopting this approach, the NaN errors in IE were successfully eliminated, achieving consistent date handling across different browsers.
The above is the detailed content of Why Does IE Date Constructor Differ from Chrome and Firefox Date Handling?. For more information, please follow other related articles on the PHP Chinese website!