如何将字符串转换为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.
当前回答
转换为pt-BR格式:
var dateString = "13/10/2014";
var dataSplit = dateString.split('/');
var dateConverted;
if (dataSplit[2].split(" ").length > 1) {
var hora = dataSplit[2].split(" ")[1].split(':');
dataSplit[2] = dataSplit[2].split(" ")[0];
dateConverted = new Date(dataSplit[2], dataSplit[1]-1, dataSplit[0], hora[0], hora[1]);
} else {
dateConverted = new Date(dataSplit[2], dataSplit[1] - 1, dataSplit[0]);
}
我希望能帮助到别人!!
其他回答
//little bit of code for Converting dates
var dat1 = document.getElementById('inputDate').value;
var date1 = new Date(dat1)//converts string to date object
alert(date1);
var dat2 = document.getElementById('inputFinishDate').value;
var date2 = new Date(dat2)
alert(date2);
只是新日期(st);
假设这是正确的格式。
还有另一种方式:
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
日期。解析几乎可以得到你想要的。它在上午/下午部分窒息,但通过一些黑客你可以让它工作:
var str = 'Sun Apr 25, 2010 3:30pm',
timestamp;
timestamp = Date.parse(str.replace(/[ap]m$/i, ''));
if(str.match(/pm$/i) >= 0) {
timestamp += 12 * 60 * 60 * 1000;
}
新的日期(2000,10,1)将给你“星期三11月1日2000 00:00:00 GMT+0100 (CET)”
0表示month,表示1月