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

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

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

当前回答

我已经创建了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)

其他回答

时间戳应该转换为一个数字

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
var date = new Date(year, month, day);

or

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

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

将其作为参数传递给Date():

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

您可以使用,例如:dt.getMonth()来访问日期、月、年。

我已经创建了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)

在我看来,这是最好、最简单的解决方案:

只需将日期字符串(使用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