How can I convert string to datetime with format specification in JavaScript?

前端 未结 15 1022
终归单人心
终归单人心 2020-11-22 02:35

How can I convert a string to a date time object in javascript by specifying a format string?

I am looking for something like:

var dateTime = convert         


        
相关标签:
15条回答
  • 2020-11-22 03:24

    Check out Moment.js. It is a modern and powerful library that makes up for JavaScript's woeful Date functions (or lack thereof).

    0 讨论(0)
  • 2020-11-22 03:26

    @Christoph Mentions using a regex to tackle the problem. Here's what I'm using:

    var dateString = "2010-08-09 01:02:03";
    var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
    var dateArray = reggie.exec(dateString); 
    var dateObject = new Date(
        (+dateArray[1]),
        (+dateArray[2])-1, // Careful, month starts at 0!
        (+dateArray[3]),
        (+dateArray[4]),
        (+dateArray[5]),
        (+dateArray[6])
    );
    

    It's by no means intelligent, just configure the regex and new Date(blah) to suit your needs.

    Edit: Maybe a bit more understandable in ES6 using destructuring:

    let dateString = "2010-08-09 01:02:03"
      , reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/
      , [, year, month, day, hours, minutes, seconds] = reggie.exec(dateString)
      , dateObject = new Date(year, month-1, day, hours, minutes, seconds);
    

    But in all honesty these days I reach for something like Moment

    0 讨论(0)
  • 2020-11-22 03:26
    time = "2017-01-18T17:02:09.000+05:30"
    
    t = new Date(time)
    
    hr = ("0" + t.getHours()).slice(-2);
    min = ("0" + t.getMinutes()).slice(-2);
    sec = ("0" + t.getSeconds()).slice(-2);
    
    t.getFullYear()+"-"+t.getMonth()+1+"-"+t.getDate()+" "+hr+":"+min+":"+sec
    
    0 讨论(0)
提交回复
热议问题