如何将字符串转换为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 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;
}
其他回答
//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);
你可以使用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月
如果在转换为Date格式之前需要检查字符串的内容:
// Convert 'M/D/YY' to Date()
mdyToDate = function(mdy) {
var d = mdy.split(/[\/\-\.]/, 3);
if (d.length != 3) return null;
// Check if date is valid
var mon = parseInt(d[0]),
day = parseInt(d[1]),
year= parseInt(d[2]);
if (d[2].length == 2) year += 2000;
if (day <= 31 && mon <= 12 && year >= 2015)
return new Date(year, mon - 1, day);
return null;
}