我有这样的 json 日期时间 2013-11-09T00:00:00
我想使用 Jquery 或 javascript 从此字符串中提取日期?
最佳答案
获胜者是:
var date = new Date(
jsonDate
.replace("T"," ")
.replace(/-/g,"/")
);
因为这是唯一可以在 IE AND FX AND Chrome 中运行的
var jsonDate = "2013-11-09T00:00:00";
var date = new Date(Date.parse(jsonDate));
console.log("With parse\t\t"+date);
date = new Date(jsonDate);
console.log("Without parse\t\t"+date);
date = new Date(jsonDate.replace("T", " "));
console.log("Without T\t\t"+date);
date = new Date(jsonDate.replace("T", " ").replace(/-/g, "/"));
console.log("Without T and dash\t"+date);
var dayNames = ["Sun", "Mon", "Tues", "Wed", "Thu", "Fri", "Sat"],
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
pad = function(str) {
return ("0" + str).slice(-2);
}
function formatDateStr(dStr) {
var date = new Date(dStr.replace("T", " ").replace(/-/g, "/"));
// Sat Nov 09 2013
return dayNames[date.getDay()] +
" " + monthNames[date.getMonth()] +
" " + pad(date.getDate()) +
" " + date.getFullYear();
}
console.log(formatDateStr("2013-11-09T00:00:00"));
var jsonDate = "2013-11-09T00:00:00";
Chrome 中为 1AM,IE8 中为 NaN,Fx 中为 OK:
var date = new Date(Date.parse(jsonDate));
window.console&&console.log("With parse "+date);
Chrome 中为 1AM,IE8 中为 NaN,Fx 中为 OK:
var date = new Date(jsonDate)
window.console&&console.log("Without parse "+date);
Chrome 中正常,IE8 中为 NaN,Fx 中日期无效:
date = new Date(jsonDate.replace("T"," "));
window.console&&console.log("Without T "+date);
在 Chrome 中正常,在 IE8 中正常,在 Fx 中正常:
date = new Date(jsonDate.replace("T"," ").replace(/-/g,"/"));
window.console&&console.log("Without T and dash "+date);
更新 - 格式:
在 Chrome 和 Fx 中,您可能会使用 .split("") 并获取前 4 个条目,但在 IE 中,您将得到 Sat Nov 9 00:00:00 UTC+0100 2013
- 并且 toLocaleString 在我的盒子上给出 11/9/2013 12:00:00 AM
var dayNames = ["Sun","Mon","Tues","Wed","Thu","Fri","Sat"],
monthNames= ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],
pad=function(str) {return ("0"+str).slice(-2);}
function formatDateStr(dStr) {
var date = new Date(dStr.replace("T"," ").replace(/-/g,"/"));
// Sat Nov 09 2013
return dayNames[date.getDay()]+
" "+monthNames[date.getMonth()]+
" "+pad(date.getDate())+
" "+date.getFullYear();
}
window.console&&console.log(formatDateStr("2013-11-09T00:00:00"));
关于javascript - 如何从日期时间json中提取日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20122953/