如何将字符串转换为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.
当前回答
在我看来,这是最好、最简单的解决方案:
只需将日期字符串(使用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
其他回答
你还可以: mydate.toLocaleDateString ();
我已经创建了parseDateTime函数将字符串转换为日期对象,它在所有浏览器(包括IE浏览器)中工作,检查是否有人需要,引用 https://github.com/Umesh-Markande/Parse-String-to-Date-in-all-browser
function parseDateTime(datetime) {
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
if(datetime.split(' ').length == 3){
var date = datetime.split(' ')[0];
var time = datetime.split(' ')[1].replace('.00','');
var timearray = time.split(':');
var hours = parseInt(time.split(':')[0]);
var format = datetime.split(' ')[2];
var bits = date.split(/\D/);
date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
if ((format === 'PM' || format === 'pm') && hours !== 12) {
hours += 12;
try{ time = hours+':'+timearray[1]+':'+timearray[2] }catch(e){ time = hours+':'+timearray[1] }
}
var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + ' ' + year + ' ' + time);
return formateddatetime;
}else if(datetime.split(' ').length == 2){
var date = datetime.split(' ')[0];
var time = datetime.split(' ')[1];
var bits = date.split(/\D/);
var datetimevalue = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
var day = datetimevalue.getDate();
var monthIndex = datetimevalue.getMonth();
var year = datetimevalue.getFullYear();
var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + ' ' + year + ' ' + time);
return formateddatetime;
}else if(datetime != ''){
var bits = datetime.split(/\D/);
var date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
return date;
}
return datetime;
}
var date1 = '2018-05-14 05:04:22 AM'; // yyyy-mm-dd hh:mm:ss A
var date2 = '2018/05/14 05:04:22 AM'; // yyyy/mm/dd hh:mm:ss A
var date3 = '2018/05/04'; // yyyy/mm/dd
var date4 = '2018-05-04'; // yyyy-mm-dd
var date5 = '2018-05-14 15:04:22'; // yyyy-mm-dd HH:mm:ss
var date6 = '2018/05/14 14:04:22'; // yyyy/mm/dd HH:mm:ss
console.log(parseDateTime(date1))
console.log(parseDateTime(date2))
console.log(parseDateTime(date3))
console.log(parseDateTime(date4))
console.log(parseDateTime(date5))
console.log(parseDateTime(date6))
**Output---**
Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time)
Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time)
Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time)
Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time)
Mon May 14 2018 15:04:22 GMT+0530 (India Standard Time)
Mon May 14 2018 14:04:22 GMT+0530 (India Standard Time)
你可以使用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));
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}
还有一种方法是在格式字符串上构建一个带有命名捕获组的正则表达式,然后使用该正则表达式从日期字符串中提取日、月和年:
function parseDate(dateStr, format) { const regex = format.toLocaleLowerCase() .replace(/\bd+\b/, '(?<day>\\d+)') .replace(/\bm+\b/, '(?<month>\\d+)') .replace(/\by+\b/, '(?<year>\\d+)') const parts = new RegExp(regex).exec(dateStr) || {}; const { year, month, day } = parts.groups || {}; return parts.length === 4 ? new Date(year, month-1, day) : undefined; } const printDate = x => console.log(x ? x.toLocaleDateString() : x); printDate(parseDate('05/11/1896', 'dd/mm/YYYY')); printDate(parseDate('07-12-2000', 'dd-mm-yy')); printDate(parseDate('07:12:2000', 'dd:mm:yy')); printDate(parseDate('2017/6/3', 'yy/MM/dd')); printDate(parseDate('2017-6-15', 'y-m-d')); printDate(parseDate('2015 6 25', 'y m d')); printDate(parseDate('2015625', 'y m d')); // bad format