4

The code: new Date('2011-12-15 00:00:00') is showing as NaN.
How can I convert this date? Any helps are appreciated.

My code is very straight forward. It works in Chrome but not in IE 9.

var dateText = new Date('2012-08-01 00:00:00'); 
alert(dateText.getDate().toString() + "/" + dateText.getMonth().toString() + "/" + dateText.getYear().toString());
Tiago Sippert
  • 1,324
  • 7
  • 24
  • 33
user007
  • 1,504
  • 2
  • 18
  • 51
  • 8
    it's a date object, not a number, so if you're trying to cast it to int, it'll be NaN. But can't give a good answer without seeing a bit more of your code and what you're trying to do with it. Show us how you're getting NaN. – Spudley Aug 07 '12 at 20:26
  • 1
    In case it's related, there's a bug in Safari/iOS which prevents that format from working... http://stackoverflow.com/a/4310986/29 – Michael Haren Aug 07 '12 at 20:28
  • 3
    I works perfectly fine here: http://jsfiddle.net/jfriend00/RvAyu/. There must be something else wrong with your code that you are not showing us. – jfriend00 Aug 07 '12 at 20:28
  • The above code does not work in IE, works in Chrome. I am sorry for not mention that here. I am using IE 9 and my organization's default browser is IE 8 or 9. – user007 Aug 07 '12 at 21:13
  • @Spudley My code is very straight forward. It works in Chrome but not in IE 9. `var dateText = new Date('2012-08-01 00:00:00'); alert(dateText.getDate().toString() + "/" + dateText.getMonth().toString() + "/" + dateText.getYear().toString());` – user007 Aug 07 '12 at 21:17

3 Answers3

6

Add "T" to the date format. e.g:

new Date('2011-12-15T00:00:00')
Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
0

After some search in web, realized that the stupid IE does not understand this date format. I do not know about Safari and Firefox, but certainly this works in Chrome.

Either I will have to use some javascript libraries like DateJS for doing this or will have to do some custom coding as below which I will never recommend. Fortunately in my case, I am sure that I will be getting the dates in the YYYY-MM-DD HH:MI:SS format.

var dateText = '2011-12-15 00:00:00';
alert(dateText.substring(5, 7) + "/" + dateText.substring(8, 10) + "/" + dateText.substring(0, 4));
user007
  • 1,504
  • 2
  • 18
  • 51
0

The easy solution I tried Download date.js from http://datejs.com/ Include in your file then var date = Date.parse('1970-01-12 00:00:00'); var formattedDate = date.toString('yyyy-MM-dd');

It works like charm in Safari.

i.AsifNoor
  • 587
  • 5
  • 14
  • I had already mentioned about DateJS in my [answer](http://stackoverflow.com/a/11854411/740756). It was just a waste to include one more js library for just this case. new Date('2011-12-15 00:00:00') does not work only in IE. My intranet is mostly accessed by IE users and Safari or FF was irrelevant for me. – user007 Apr 16 '14 at 17:19