Javascript date returning NAN in IE8

佐手、 提交于 2019-12-22 10:27:10

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/13758581/javascript-date-returning-nan-in-ie8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!