gpt4 book ai didi

javascript - 如何从日期时间 json 中提取日期?

转载 作者:行者123 更新时间:2023-11-29 17:13:15 26 4
gpt4 key购买 nike

我有这样的 json 日期时间 2013-11-09T00:00:00 我想使用 Jquery 或 javascript 从这个字符串中提取日期?

最佳答案

获胜者是:

var date = new Date(
jsonDate
.replace("T"," ")
.replace(/-/g,"/")
);

因为这是唯一在 IE、FX 和 Chrome 中工作的

JSFiddle

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";

1AM 在 Chrome 中,在 IE8 中为 NaN,在 Fx 中为 OK:

var date = new Date(Date.parse(jsonDate));
window.console&&console.log("With parse "+date);

1AM 在 Chrome 中,在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com