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

前端 未结 15 1055
终归单人心
终归单人心 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条回答
  •  旧时难觅i
    2020-11-22 03:19

    External library is an overkill for parsing one or two dates, so I made my own function using Oli's and Christoph's solutions. Here in central Europe we rarely use aything but the OP's format, so this should be enough for simple apps used here.

    function ParseDate(dateString) {
        //dd.mm.yyyy, or dd.mm.yy
        var dateArr = dateString.split(".");
        if (dateArr.length == 1) {
            return null;    //wrong format
        }
        //parse time after the year - separated by space
        var spacePos = dateArr[2].indexOf(" ");
        if(spacePos > 1) {
            var timeString = dateArr[2].substr(spacePos + 1);
            var timeArr = timeString.split(":");
            dateArr[2] = dateArr[2].substr(0, spacePos);
            if (timeArr.length == 2) {
                //minutes only
                return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]));
            } else {
                //including seconds
                return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]), parseInt(timeArr[2]))
            }
        } else {
            //gotcha at months - January is at 0, not 1 as one would expect
            return new Date(parseInt(dateArr[2]), parseInt(dateArr[1] - 1), parseInt(dateArr[0]));
        }
    }
    

提交回复
热议问题