Parse 'Date & Time' string in Javascript which are of custom format

前端 未结 5 1050
-上瘾入骨i
-上瘾入骨i 2020-11-30 10:08

I have to parse a date and time string of format \"2015-01-16 22:15:00\". I want to parse this into JavaScript Date Object. Any help on this?

I tried some jquery plu

相关标签:
5条回答
  • 2020-11-30 10:31

    With moment.js you can create a moment object using the String+Format constructor:

    var momentDate = moment('2015-01-16 22:15:00', 'YYYY-MM-DD HH:mm:ss');
    

    Then, you can convert it to JavaScript Date Object using toDate() method:

    var jsDate = momentDate.toDate();
    
    0 讨论(0)
  • 2020-11-30 10:36

    A better solution, I am now using date.js - https://code.google.com/p/datejs/

    I included the script in my html page as this -

    <script type="text/javascript" src="path/to/date.js"></script>
    

    Then I simply parsed the date string "2015-01-16 22:15:00" with specifying the format as,

    var dateString = "2015-01-16 22:15:00";
    var date = Date.parse(dateString, "yyyy-MM-dd HH:mm:ss");
    
    0 讨论(0)
  • 2020-11-30 10:44

    If you are sure it's in the desired format and don't need to error check, you can parse it manually using split (and optionally replace). I needed to do something similar in my project (MM/DD/YYYY HH:mm:ss:sss) and modified my solution to fit your format. Notice the subtraction of 1 in the month.

    var str = "2015-01-16 22:15:00"; 
    //Replace dashes and spaces with : and then split on :
    var strDate = str.replace(/-/g,":").replace(/ /g,":").split(":");
    var aDate = new Date(strDate[0], strDate[1]-1, strDate[2], strDate[3], strDate[4], strDate[5]) ; 
    
    0 讨论(0)
  • 2020-11-30 10:51

    I was trying to use moment.js guys. But since I was having this error, "ReferenceError: moment is not defined", I had to skip it for now. I am using an temporary workaround for now.

    function parseDate(dateString) {
        var dateTime = dateString.split(" ");
        var dateOnly = dateTime[0];
        var timeOnly = dateTime[1];
    
        var temp = dateOnly + "T" + timeOnly;
        return new Date(temp);
    }
    
    0 讨论(0)
  • new Date("2015-01-16T22:15:00")
    

    See Date.parse().

    The string must be in the ISO-8601 format. If you want to parse other formats use moment.js.

    moment("2015-01-16 22:15:00").toDate();
    
    0 讨论(0)
提交回复
热议问题