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

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

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

当前回答

我使用这个函数将任何Date对象转换为UTC Date对象。

function dateToUTC(date) {
    return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}


dateToUTC(new Date());

其他回答

只是新日期(st);

假设这是正确的格式。

ISO 8601式的数据字符串,尽管标准很优秀,但仍然没有得到广泛的支持。

这是一个很好的资源来找出你应该使用哪种datestring格式:

http://dygraphs.com/date-formats.html

是的,这意味着你的datestring可以简单的反对

“2014/10/13 23:57:52” 而不是 “2014-10-13 23:57:52”

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

我已经为此创建了一个小提琴,你可以在任何日期字符串上使用toDate()函数并提供日期格式。这将返回一个Date对象。 https://jsfiddle.net/Sushil231088/q56yd0rp/

"17/9/2014".toDate("dd/MM/yyyy", "/")