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

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

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

当前回答

建议:我建议使用包含很多格式的日期包,因为时区和格式时间管理确实是一个大问题,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/

其他回答

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

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

性能

今天(2020.05.08),我对所选解决方案进行了测试-有两种情况:输入日期是ISO8601字符串(Ad,Bd,Cd,Dd,Ed),输入日期是时间戳(At, Ct, Dt)。解决方案Bd,Cd,Ct不返回js Date对象作为结果,但我添加它们,因为它们可能是有用的,但我没有将它们与有效的解决方案进行比较。该结果对于大量数据解析非常有用。

结论

解决方案new Date (Ad)比moment.js (Dd)快50-100倍,适用于所有浏览器的ISO日期和时间戳 解决方案new Date (Ad)比parseDate (Ed)快10倍 解决方案date .parse(Bd)是最快的,如果我们需要在所有浏览器上从ISO日期获得时间戳

细节

我在MacOs High Sierra 10.13.6、Chrome 81.0、Safari 13.1、Firefox 75.0上进行测试。解决方案parseDate (Ed)使用新的Date(0)和手动设置UTC日期组件。

let ds = '2020-05-14T00:00Z'; // Valid ISO8601 UTC date let ts = +'1589328000000'; // timestamp let Ad = new Date(ds); let Bd = Date.parse(ds); let Cd = moment(ds); let Dd = moment(ds).toDate(); let Ed = parseDate(ds); let At = new Date(ts); let Ct = moment(ts); let Dt = moment(ts).toDate(); log = (n,d) => console.log(`${n}: ${+d} ${d}`); console.log('from date string:', ds) log('Ad', Ad); log('Bd', Bd); log('Cd', Cd); log('Dd', Dd); log('Ed', Ed); console.log('from timestamp:', ts) log('At', At); log('Ct', Ct); log('Dt', Dt); function parseDate(dateStr) { let [year,month,day] = dateStr.split(' ')[0].split('-'); let d=new Date(0); d.setUTCFullYear(year); d.setUTCMonth(month-1); d.setUTCDate(day) return d; } <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment-with-locales.min.js"></script> This snippet only presents used soultions

铬检测结果

建议:我建议使用包含很多格式的日期包,因为时区和格式时间管理确实是一个大问题,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/

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

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