如何将字符串转换为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

其他回答

var date = new Date(year, month, day);

or

var date = new Date('01/01/1970');

格式为“01-01-1970”的日期字符串在FireFox中行不通,所以最好在日期格式字符串中使用“/”而不是“-”。

你可以使用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));

对于在js中转换字符串到日期,我使用http://momentjs.com/

moment().format('MMMM Do YYYY, h:mm:ss a'); // August 16th 2015, 4:17:24 pm
moment().format('dddd');                    // Sunday
moment().format("MMM Do YY");               // Aug 16th 15
moment().format('YYYY [escaped] YYYY');     // 2015 escaped 2015
moment("20111031", "YYYYMMDD").fromNow(); // 4 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow();        // 16 hours ago
moment().endOf('day').fromNow();          // in 8 hours

使用这段代码:(我的问题已经用这段代码解决了)

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;

}

这个答案是基于卡塞姆的答案,但它也适用于两位数的年份。我对卡塞姆的答案进行了编辑,但以防它没有被批准,我还将这个作为单独的答案提交。

function stringToDate(_date,_format,_delimiter) {
        var formatLowerCase=_format.toLowerCase();
        var formatItems=formatLowerCase.split(_delimiter);
        var dateItems=_date.split(_delimiter);
        var monthIndex=formatItems.indexOf("mm");
        var dayIndex=formatItems.indexOf("dd");
        var yearIndex=formatItems.indexOf("yyyy");
        var year = parseInt(dateItems[yearIndex]); 
        // adjust for 2 digit year
        if (year < 100) { year += 2000; }
        var month=parseInt(dateItems[monthIndex]);
        month-=1;
        var formatedDate = new Date(year,month,dateItems[dayIndex]);
        return formatedDate;
}

stringToDate("17/9/14","dd/MM/yyyy","/");
stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")