Home > Article > Web Front-end > Does IE\'s Date Constructor Cause NaN Errors in Cross-Browser Date Conversions?
IE Date Constructor Returns NaN: A Cross-Browser Date Conversion Solution
In the realm of JavaScript date manipulation, a peculiar issue arises in Internet Explorer (IE) where the Date constructor behaves differently from its peers in Firefox and Chrome. When attempting to create a new Date object from a string, IE returns NaN (Not a Number), while the other browsers produce valid dates.
To understand this discrepancy, we need to delve into the underlying parser mechanisms used by each browser. In IE, the Date constructor struggles with certain date formats, particularly those that include commas as separators.
Here's a specific example encountered by a developer attempting to build a calendar:
<code class="javascript">function buildWeek(dateText){ var headerDates=''; var newDate = new Date(dateText); for(var d=0;d<7;d++){ headerDates += '<th>' + newDate + '</th>'; newDate.setDate(newDate.getDate()+1); } jQuery('div#headerDates').html('<table><tr>'+headerDates+'</tr></table>'); }</code>
In this function, the dateText parameter represents the Monday of the current week, formatted as 'm, d, Y' (e.g., "02, 01, 2010"). While this format works seamlessly in Firefox and Chrome, it poses a challenge in IE, which fails to parse the comma-separated values correctly.
To resolve this issue, we can utilize a more consistent and cross-browser compatible date format. One such approach is to convert the comma-separated string into an array of discrete values, which can then be used to construct a valid Date object:
<code class="javascript">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]);</code>
In this example, the dateStr variable represents the date and time retrieved from a MySQL database in the format 'YYYY-MM-DD HH:MM:SS'. By splitting this string into its component parts and passing them individually to the Date constructor, we ensure that the conversion is handled consistently across browsers.
This solution addresses the cross-browser date parsing discrepancy and enables the buildWeek function to work seamlessly in all major browsers, including Internet Explorer.
The above is the detailed content of Does IE\'s Date Constructor Cause NaN Errors in Cross-Browser Date Conversions?. For more information, please follow other related articles on the PHP Chinese website!