我正在尝试解析日期,就像我以字符串格式从数据库接收的2012-12-07T16:18:15+05:30
一样。
我正在使用的解析函数是:
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();
然而, IE8浏览器在第一行返回NAN ,即jstime在IE8中是NAN,而在其他浏览器中工作正常。
那么,有没有其他方法可以解析在所有浏览器中都运行良好的日期?
我需要以上述格式接受日期&以格式返回日期:
Fri Dec 07 2012,4:18:15 pm
?
答案 0 :(得分:3)
如果您可以确定格式,可以正确使用它:
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));
但如果它来自服务器端,您可以在那里更可靠地格式化它。
答案 1 :(得分:-1)
你可以这样做 -
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 .....
我认为这会对你有帮助。