Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 947
Chirag Rupani Avatar asked Jul 17 '26 04:07

Chirag Rupani


1 Answers

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.

like image 93
Niet the Dark Absol Avatar answered Jul 18 '26 18:07

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!