How to extract date from string using javascript

后端 未结 5 1457
轮回少年
轮回少年 2021-01-21 11:35

How does one extract a date from a string using javascript? It can be in the following formats:

31.07.2014

07.31.2014

2014.07.31 the same format but divi

5条回答
  •  生来不讨喜
    2021-01-21 12:23

    Maybe this could help you (Demo Fiddle here):

    function getDate(d)
    {
        var day, month, year;
    
        result = d.match("[0-9]{2}([\-/ \.])[0-9]{2}[\-/ \.][0-9]{4}");
        if(null != result) {
            dateSplitted = result[0].split(result[1]);
            day = dateSplitted[0];
            month = dateSplitted[1];
            year = dateSplitted[2];
        }
        result = d.match("[0-9]{4}([\-/ \.])[0-9]{2}[\-/ \.][0-9]{2}");
        if(null != result) {
            dateSplitted = result[0].split(result[1]);
            day = dateSplitted[2];
            month = dateSplitted[1];
            year = dateSplitted[0];
        }
    
        if(month>12) {
            aux = day;
            day = month;
            month = aux;
        }
    
        return year+"/"+month+"/"+day;
    }
    

提交回复
热议问题