Date constructor returns NaN in IE, but works in Firefox and Chrome

I am trying to create a small calendar in JavaScript. I have good dates in Firefox and Chrome, but in IE, date functions return NaN.

Here is the function:

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>'); } 

dateText is the Monday of the current week, which is actually set to php in the format "m, d, Y", for example. "02, 01, 2010" .

+68
javascript date internet-explorer
02 Feb '10 at 6:27
source share
11 answers

The Date constructor takes any value. If the primitive [[value]] of the argument is a number, then the created date has this value. If primitive [[value]] is a String, the specification ensures that the Date constructor and parse method are able to parse the result of Date.prototype.toString and Date.prototype.toUTCString ()

A reliable way to set the date is to build one and use the setFullYear and setTime .

An example of this: http://jibbering.com/faq/#parseDate

ECMA-262 r3 does not detect date formats. Passing string values ​​to the Date or Date.parse constructor has an implementation-dependent result. Best avoided.




Edit: Record from frequently asked questions in comp.lang.javascript: Extended date format ISO 8601 YYYY-MM-DD can be analyzed using Date with the following: -
 /**Parses string formatted as YYYY-MM-DD to a Date object. * If the supplied string does not match the format, an * invalid Date (value NaN) is returned. * @param {string} dateStringInRange format YYYY-MM-DD, with year in * range of 0000-9999, inclusive. * @return {Date} Date object representing the string. */ function parseISO8601(dateStringInRange) { var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/, date = new Date(NaN), month, parts = isoExp.exec(dateStringInRange); if(parts) { month = +parts[2]; date.setFullYear(parts[1], month - 1, parts[3]); if(month != date.getMonth() + 1) { date.setTime(NaN); } } return date; } 
+62
Feb 02 2018-10-02T00
source share

From the mysql format datetime / timestamp:

 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]); 

I hope this is helpful to someone. Works in IE FF Chrome

+79
Aug 04 2018-11-11T00:
source share

Do not use "new date ()" because it takes the date input string as local time:

 new Date('11/08/2010').getTime()-new Date('11/07/2010').getTime(); //90000000 new Date('11/07/2010').getTime()-new Date('11/06/2010').getTime(); //86400000 

we must use "NewDate ()", it takes data as GMT:

 function NewDate(str) {str=str.split('-'); var date=new Date(); date.setUTCFullYear(str[0], str[1]-1, str[2]); date.setUTCHours(0, 0, 0, 0); return date; } NewDate('2010-11-07').toGMTString(); NewDate('2010-11-08').toGMTString(); 
+15
Dec 01 2018-10-12T00:
source share

Here's another approach that adds a method to a Date object

usage: var d = (new Date()).parseISO8601("1971-12-15");

     / **
      * Parses the ISO 8601 formated date into a date object, ISO 8601 is YYYY-MM-DD
      * 
      * @param {String} date the date as a string eg 1971-12-15
      * @returns {Date} Date object representing the date of the supplied string
      * /
     Date.prototype.parseISO8601 = function (date) {
         var matches = date.match (/ ^ \ s * (\ d {4}) - (\ d {2}) - (\ d {2}) \ s * $ /);

         if (matches) {
             this.setFullYear (parseInt (matches [1]));    
             this.setMonth (parseInt (matches [2]) - 1);    
             this.setDate (parseInt (matches [3]));    
         }

         return this;
     };
+7
Dec 22 '11 at 2:06 p.m.
source share

Here is a piece of code that captures this IE behavior (v ['date'] is a comma-separated date-string, for example, "2010,4,1"):

 if($.browser.msie){ $.lst = v['date'].split(','); $.tmp = new Date(parseInt($.lst[0]),parseInt($.lst[1])-1,parseInt($.lst[2])); } else { $.tmp = new Date(v['date']); } 

The previous approach did not take into account that the month of JS Date is based on ZERO ...

Sorry for not explaining too much, I'm at work and just thought it might help.

+2
Jul 22 2018-11-11T00:
source share

I always store the date in UTC.

This is my own function made from various functions that I found on this page.

The mysql DATETIME format requires STRING (example: 2013-06-15 15:21:41). Regular expression validation is optional. You can remove this part to improve performance.

This function returns a timestamp.

DATETIME is treated as a UTC date . Be careful: if you expect local datetime, this function is not for you.

  function datetimeToTimestamp(datetime) { var regDatetime = /^[0-9]{4}-(?:[0]?[0-9]{1}|10|11|12)-(?:[012]?[0-9]{1}|30|31)(?: (?:[01]?[0-9]{1}|20|21|22|23)(?::[0-5]?[0-9]{1})?(?::[0-5]?[0-9]{1})?)?$/; if(regDatetime.test(datetime) === false) throw("Wrong format for the param. `Ymd H:i:s` expected."); var a=datetime.split(" "); var d=a[0].split("-"); var t=a[1].split(":"); var date = new Date(); date.setUTCFullYear(d[0],(d[1]-1),d[2]); date.setUTCHours(t[0],t[1],t[2], 0); return date.getTime(); } 
+2
Jul 03 '13 at 17:20
source share

Send the text and date format to which you are sending the datetext in the following way. It will parse and return as a date, and it is browser independent.

 function cal_parse_internal(val, format) { val = val + ""; format = format + ""; var i_val = 0; var i_format = 0; var x, y; var now = new Date(dbSysCurrentDate); var year = now.getYear(); var month = now.getMonth() + 1; var date = now.getDate(); while (i_format < format.length) { // Get next token from format string var c = format.charAt(i_format); var token = ""; while ((format.charAt(i_format) == c) && (i_format < format.length)) { token += format.charAt(i_format++); } // Extract contents of value based on format token if (token == "yyyy" || token == "yy" || token == "y") { if (token == "yyyy") { x = 4; y = 4; } if (token == "yy") { x = 2; y = 2; } if (token == "y") { x = 2; y = 4; } year = _getInt(val, i_val, x, y); if (year == null) { return 0; } i_val += year.length; if (year.length == 2) { if (year > 70) { year = 1900 + (year - 0); } else { year = 2000 + (year - 0); } } } else if (token == "MMMM") { month = 0; for (var i = 0; i < MONTHS_LONG.length; i++) { var month_name = MONTHS_LONG[i]; if (val.substring(i_val, i_val + month_name.length) == month_name) { month = i + 1; i_val += month_name.length; break; } } if (month < 1 || month > 12) { return 0; } } else if (token == "MMM") { month = 0; for (var i = 0; i < MONTHS_SHORT.length; i++) { var month_name = MONTHS_SHORT[i]; if (val.substring(i_val, i_val + month_name.length) == month_name) { month = i + 1; i_val += month_name.length; break; } } if (month < 1 || month > 12) { return 0; } } else if (token == "MM" || token == "M") { month = _getInt(val, i_val, token.length, 2); if (month == null || month < 1 || month > 12) { return 0; } i_val += month.length; } else if (token == "dd" || token == "d") { date = _getInt(val, i_val, token.length, 2); if (date == null || date < 1 || date > 31) { return 0; } i_val += date.length; } else { if (val.substring(i_val, i_val+token.length) != token) {return 0;} else {i_val += token.length;} } } // If there are any trailing characters left in the value, it doesn't match if (i_val != val.length) { return 0; } // Is date valid for month? if (month == 2) { // Check for leap year if ((year%4 == 0 && year%100 != 0) || (year%400 == 0)) { // leap year if (date > 29) { return false; } } else { if (date > 28) { return false; } } } if (month == 4 || month == 6 || month == 9 || month == 11) { if (date > 30) { return false; } } return new Date(year, month - 1, date); } 
+1
Feb 02 2018-10-02T00
source share

Here is my approach:

 var parseDate = function(dateArg) { var dateValues = dateArg.split('-'); var date = new Date(dateValues[0],dateValues[1],dateValues[2]); return date.format("m/d/Y"); } 

replace ('-') with the separator you are using.

+1
Apr 6
source share

JavaScript's Date constructor needs a string in one of the date formats supported by the parse () method.

Apparently, the format you specify is not supported in IE, so you need to either modify the PHP code or parse the string manually in JavaScript.

0
Feb 02 '10 at 6:35
source share

You can use the following code to parse an ISO8601 date string:

 function parseISO8601(d) { var timestamp = d; if (typeof (d) !== 'number') { timestamp = Date.parse(d); } return new Date(timestamp); }; 
0
Apr 01 '14 at 9:13
source share

Try using the getDate datepicker function.

 $.datepicker.formatDate('yy-mm-dd',new Date(pField.datepicker("getDate"))); 
0
Jul 18 '16 at 6:09
source share



All Articles