Javascript新的日期跨浏览器格式问题 [英] Javascript new Date Cross Browser Format Problem
本文介绍了Javascript新的日期跨浏览器格式问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用Javascript格式化日期字符串时遇到问题。在IE上,日期格式为MM-DD-YYYY,但在Firefox上,日期格式为YYYY-MM-DD。 Chrome可以同时使用这两种格式,但是当我选择其中一种格式时,另一种浏览器会向我发出无效日期警告。
I'm having problems with date string formatting using Javascript. On IE the date format is MM-DD-YYYY but on Firefox it's YYYY-MM-DD. Chrome works both of them but when I choose one of the formats, the other browser gives me an Invalid Date warning.
我的代码为例(在IE上有效,但不适用于IE)在Firefox上):
My code as an example (works on IE but not on Firefox):
var dateSTR = "2015-09-29";
var date = new Date(dateSTR.replace(/(\d{4})-(\d{2})-(\d{2})/,"$2-$3-$1"));
date.setUTCHours(date.getHours());
date.setUTCMinutes(date.getMinutes());
return date.toLocaleDateString();
https://jsfiddle.net/kmmna8c0/
推荐答案
我只看到toLocaleDateString有所不同-注意:我在欧洲,所以只有FX在显示我想要的东西
I only see a difference in the toLocaleDateString - NOTE: I am in Europe, so only FX is showing me what I want
var dateSTR = "2015-09-29";
var date = new Date(dateSTR.replace(/-/g,"/"));
console.log("0:"+ new Date("2015/09/29"))
console.log("1:"+date)
date.setUTCHours(date.getHours());
console.log("2:"+date)
date.setUTCMinutes(date.getMinutes());
console.log("3:"+date);
console.log("4:"+date.toLocaleDateString());
Chrome:
0:Tue Sep 29 2015 00:00:00 GMT+0200 (W. Europe Daylight Time)
1:Tue Sep 29 2015 00:00:00 GMT+0200 (W. Europe Daylight Time)
2:Mon Sep 28 2015 02:00:00 GMT+0200 (W. Europe Daylight Time)
3:Mon Sep 28 2015 02:00:00 GMT+0200 (W. Europe Daylight Time)
4:9/28/2015
IE10 :
0:Tue Sep 29 00:00:00 UTC+0200 2015
1:Tue Sep 29 00:00:00 UTC+0200 2015
2:Mon Sep 28 02:00:00 UTC+0200 2015
3:Mon Sep 28 02:00:00 UTC+0200 2015
4:28 September 2015
FX:
"0:Tue Sep 29 2015 00:00:00 GMT+0200"
"1:Tue Sep 29 2015 00:00:00 GMT+0200"
"2:Mon Sep 28 2015 02:00:00 GMT+0200"
"3:Mon Sep 28 2015 02:00:00 GMT+0200"
"4:28/09/2015"
这篇关于Javascript新的日期跨浏览器格式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文