如何将字符串转换为JavaScript日期对象?

var st = "date in some format"
var dt = new Date();

var dt_st = // st in Date format, same as dt.

当前回答

你可以试试这个:

function formatDate(userDOB) { const dob = new Date(userDOB); const monthNames = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; const day = dob.getDate(); const monthIndex = dob.getMonth(); const year = dob.getFullYear(); // return day + ' ' + monthNames[monthIndex] + ' ' + year; return `${day} ${monthNames[monthIndex]} ${year}`; } console.log(formatDate('1982-08-10'));

其他回答

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 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 month=parseInt(dateItems[monthIndex]);
            month-=1;
            var formatedDate = new Date(dateItems[yearIndex],month,dateItems[dayIndex]);
            return formatedDate;
}

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

作为这里所解释的内容的一个插件,您可以使用new Date()创建日期,并使用非常有用的toLocaleDateString()函数对其进行格式化

一个例子:

console.log(new Date('1970-01-01').toLocaleDateString('es-ES')) //——>输出'1/1/1970'

还有另一种方式:

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
                //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);