Chirag Rupani
Chirag Rupani

Reputation: 1715

Javascript date returning NAN in IE8

I am trying to parse date like this 2012-12-07T16:18:15+05:30 which I am receiving from database in string format. The parse function I am using is:

var jstime = new Date("2012-12-07T16:18:15+05:30"); 
 var h = jstime.getHours();
var m = jstime.getMinutes();
var s = jstime.getSeconds();
var f = "am"
if(h >= 12)
{
    f = "pm";
    h = h - 12;
}
if(h == 0)
{
    h = 12;
}
var str;
str = jstime.toDateString();
str = str +"," + h.toString() + ":" + m.toString() + ":" + s.toString() + " " + f.toString(); 

However,IE8 browser returning NAN at very first line i.e. jstime is NAN in IE8,while working fine in other browsers.
so, Is there any alternate way to parse date that works well in all browsers?
I need it accepts date in above format & returns date in format: Fri Dec 07 2012,4:18:15 pm?

Upvotes: 3

Views: 2824

Answers (2)

Sandip Karanjekar
Sandip Karanjekar

Reputation: 850

You can do this -

date = Date.parse("2012-12-07T16:18:15+05:30");
var jstime = new Date(date); 
var h = jstime.getHours();
var m = jstime.getMinutes();
var s = jstime.getSeconds();
continue your code .....

I think this will help you.

Upvotes: -1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

If you can be sure of the format, you can regex it:

var match = "2012-12-07T16:18:15+05:30".match(/(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)([+-])(\d\d):(\d\d)/);
var jstime = new Date();
jstime.setUTCFullYear(parseInt(match[1],10));
jstime.setUTCMonth(parseInt(match[2],10)-1);
jstime.setUTCDate(parseInt(match[3],10));
jstime.setUTCHours(parseInt(match[4],10)-parseInt(match[7]+"1",10)*parseInt(match[8],10));
jstime.setUTCMinutes(parseInt(match[5],10)-parseInt(match[7]+"1",10)*parseInt(match[9],10));
jstime.setUTCSeconds(parseInt(match[6],10));

But if it's coming from the server-side, you may be able to format it more reliably there.

Upvotes: 3

Related Questions