如何将字符串转换为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.
当前回答
还有另一种方式:
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
其他回答
你可以使用regex解析字符串以详细的时间,然后创建日期或任何返回格式,如:
//example : let dateString = "2018-08-17 01:02:03.4"
function strToDate(dateString){
let reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}).(\d{1})/
, [,year, month, day, hours, minutes, seconds, miliseconds] = reggie.exec(dateString)
, dateObject = new Date(year, month-1, day, hours, minutes, seconds, miliseconds);
return dateObject;
}
alert(strToDate(dateString));
只是新日期(st);
假设这是正确的格式。
新的日期(2000,10,1)将给你“星期三11月1日2000 00:00:00 GMT+0100 (CET)”
0表示month,表示1月
作为这里所解释的内容的一个插件,您可以使用new Date()创建日期,并使用非常有用的toLocaleDateString()函数对其进行格式化
一个例子:
console.log(new Date('1970-01-01').toLocaleDateString('es-ES')) //——>输出'1/1/1970'
Var a = "13:15" var b = toDate(a, "h:m") / /警报(b); document . write (b); 函数toDate(dStr, format) { var now = new Date(); If (format == "h:m") { now.setHours(下游。substr (0, dStr.indexOf(“:”))); now.setMinutes(dStr.substr(dStr.indexOf(":") + 1)); now.setSeconds (0); 现在返回; 其他} 返回“格式无效”; }