如何将字符串转换为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.
当前回答
还有一种方法是在格式字符串上构建一个带有命名捕获组的正则表达式,然后使用该正则表达式从日期字符串中提取日、月和年:
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
其他回答
如果要从“dd/MM/yyyy”格式转换。这里有一个例子:
var pattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var arrayDate = stringDate.match(pattern);
var dt = new Date(arrayDate[3], arrayDate[2] - 1, arrayDate[1]);
此解决方案适用于IE 9以下版本。
在我看来,这是最好、最简单的解决方案:
只需将日期字符串(使用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
时间戳应该转换为一个数字
var ts = '1471793029764';
ts = Number(ts); // cast it to a Number
var date = new Date(ts); // works
var invalidDate = new Date('1471793029764'); // does not work. Invalid Date
你还可以: mydate.toLocaleDateString ();
使用这段代码:(我的问题已经用这段代码解决了)
function dateDiff(date1, date2){
var diff = {} // Initialisation du retour
var tmp = date2 - date1;
tmp = Math.floor(tmp/1000); // Nombre de secondes entre les 2 dates
diff.sec = tmp % 60; // Extraction du nombre de secondes
tmp = Math.floor((tmp-diff.sec)/60); // Nombre de minutes (partie entière)
diff.min = tmp % 60; // Extraction du nombre de minutes
tmp = Math.floor((tmp-diff.min)/60); // Nombre d'heures (entières)
diff.hour = tmp % 24; // Extraction du nombre d'heures
tmp = Math.floor((tmp-diff.hour)/24); // Nombre de jours restants
diff.day = tmp;
return diff;
}