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

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

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

当前回答

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

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

其他回答

建议:我建议使用包含很多格式的日期包,因为时区和格式时间管理确实是一个大问题,moment js解决了很多格式。你可以很容易地从一个简单的字符串解析日期,但我认为这是一个艰苦的工作,以支持所有格式和日期的变化。

更新:Moment现在已弃用,一个很好的Moment的替代品是datefns https://date-fns.org/


moment.js (http://momentjs.com/)是一个完整和良好的使用日期包,支持ISO 8601字符串。

您可以添加字符串日期和格式。

moment("12-25-1995", "MM-DD-YYYY");

你可以检查一个日期是否有效。

moment("not a real date").isValid(); //Returns false

一些显示示例

let dt = moment("02-01-2019", "MM-DD-YYYY");
console.log(dt.fromNow()+' |'+dt.format('LL')) 
// output: "3 months ago | February 1, 2019"

看文档 http://momentjs.com/docs/#/parsing/string-format/

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

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

我已经创建了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日期格式和JavaScript date对象构造函数。

ISO格式的例子:YYYY-MM-DD或YYYY-MM-DDTHH:MM:SS。

但是等等!仅仅使用“ISO格式”本身并不能可靠地工作。字符串有时解析为UTC,有时解析为localtime(基于浏览器供应商和版本)。最佳实践应该始终是将日期存储为UTC,并以UTC进行计算。

要将日期解析为UTC,请添加Z -例如:new date ('2011-04-11T10:20:30Z')。

使用.toUTCString()显示UTC日期, 使用. tostring()以用户的本地时间显示日期。

关于MDN |日期和这个答案的更多信息。

对于旧的Internet Explorer兼容性(小于9的IE版本在日期构造函数中不支持ISO格式),您应该将日期时间字符串表示拆分为部分,然后您可以使用使用日期时间部分的构造函数,例如:new Date('2011', '04' - 1, '11', '11', '51', '00')。注意,月份的数字必须小于1。


替代方法-使用适当的库:

您还可以利用Moment.js库,该库允许使用指定的时区解析日期。

对于在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