如何将字符串转换为JavaScript日期对象?
var st = "date in some format"
var dt = new Date();
var dt_st = // st in Date format, same as dt.
如何将字符串转换为JavaScript日期对象?
var st = "date in some format"
var dt = new Date();
var dt_st = // st in Date format, same as dt.
当前回答
var st = "26.04.2013";
var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
var dt = new Date(st.replace(pattern,'$3-$2-$1'));
输出将是:
dt => Date {Fri Apr 26 2013}
其他回答
var st = "26.04.2013";
var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
var dt = new Date(st.replace(pattern,'$3-$2-$1'));
输出将是:
dt => Date {Fri Apr 26 2013}
不幸的是,我发现了
var mydate =新日期(2014-04-03); 游戏机。log (mydate toDateString ());
返回“2014年4月2日星期三”。我知道这听起来很疯狂,但这确实发生在一些用户身上。
防弹方案如下:
Var parts ='2014-04-03'.split('-'); //请关注月份(零件[1]);JavaScript从0开始计算月份: // 1月- 0日,2月- 1日,等等。 var mydate =新的日期(部分[0],部分[1]- 1,部分[2]); console.log (mydate.toDateString ());
还有另一种方式:
String.prototype.toDate = function(format) {
format = format || "dmy";
var separator = this.match(/[^0-9]/)[0];
var components = this.split(separator);
var day, month, year;
for (var key in format) {
var fmt_value = format[key];
var value = components[key];
switch (fmt_value) {
case "d":
day = parseInt(value);
break;
case "m":
month = parseInt(value)-1;
break;
case "y":
year = parseInt(value);
}
}
return new Date(year, month, day);
};
a = "3/2/2017";
console.log(a.toDate("dmy"));
// Date 2017-02-03T00:00:00.000Z
在我看来,这是最好、最简单的解决方案:
只需将日期字符串(使用ISO格式)与“T00:00:00”连接在一起,并使用JavaScript date()构造函数,如下例所示。
const dateString = '2014-04-03'
var mydate = new Date(dateString + "T00:00:00");
console.log(mydate.toDateString());
还有上面解决方案的一些细节(可选阅读):
In ISO format, if you provide time and Z is not present in the end of string, the date will be local time zone instead of UTC time zone. That means, when setting a date in this way, without specifying the time zone, JavaScript will use the local browser's time zone. And when getting a date, without specifying the time zone as well, the result is also converted to the browser's time zone. And, by default, almost every date method in JavaScript (except one) gives you a date/time in local time zone as well (you only get UTC if you specify UTC). So, using in local/browser time zone you probably won't get unwanted results because difference between your local/browse time zone and the UTC time zone, which is one of the main complaints with date string conversion. But if you will use this solution, understand your context and be aware of what you are doing. And also be careful that omitting T or Z in a date-time string can give different results in different browsers.
值得注意的是,上面的例子会给你和下面这个例子完全一样的回报,这是这个问题中投票第二多的答案:
var parts ='2014-04-03'.split('-');
// Please pay attention to the month (parts[1]); JavaScript counts months from 0:
// January - 0, February - 1, etc.
var mydate = new Date(parts[0], parts[1] - 1, parts[2]);
console.log(mydate.toDateString());
主要的区别是,这里提供的第一个示例比第二个示例更简单,甚至更防错误(至少在我看来,如下所述)。
因为如果你调用JavaScript Date()构造函数时只带一个ISO格式的日期字符串参数(第一个例子),它就不接受超出其逻辑限制的值(因此,如果你把13作为月或32作为日,你就会得到无效日期)。
但是,当您使用具有多个日期参数的相同构造函数时(第二个示例),高于其逻辑限制的参数将被调整为相邻值,并且您不会得到无效日期错误(因此,如果您给出13作为月份,它将调整为1,而不是给出无效日期)。
或者另一种(也是第三种)解决方案将两者混合使用,使用第一个示例只是验证日期字符串,如果它是有效的,则使用第二个示例(这样可以避免第一个示例可能的浏览器不一致,同时避免参数的权限高于第二个示例的逻辑限制)。
就像这样(也接受部分日期):
function covertStringToDate(dateString) {
//dateString should be in ISO format: "yyyy-mm-dd", "yyyy-mm" or "yyyy"
if(new Date(dateString).toString() === "Invalid Date") {
return false
} else {
const onlyNumbers = dateString.replace(/\D/g, "");
const year = onlyNumbers.slice(0,4)
const month = onlyNumbers.slice(4,6)
const day = onlyNumbers.slice(6,8)
if(!month){
return(new Date(year))
} else if (!day) {
return(new Date(year, month - 1))
} else {
return(new Date(year, month - 1, day))
}
}
}
第四种选择(也是最后一个建议)是使用适当的第三个库(如moment或date-fns)
引用:
https://www.w3schools.com/js/js_date_formats.asp https://css-tricks.com/everything-you-need-to-know-about-date-in-javascript/ https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Date#parameters
ISO 8601式的数据字符串,尽管标准很优秀,但仍然没有得到广泛的支持。
这是一个很好的资源来找出你应该使用哪种datestring格式:
http://dygraphs.com/date-formats.html
是的,这意味着你的datestring可以简单的反对
“2014/10/13 23:57:52” 而不是 “2014-10-13 23:57:52”