解释用户在JavaScript中输入的日期

时间:2013-04-06 17:02:10

标签: javascript date input format interpreter

我一直在寻找一种方便的方法来获取用户输入的日期并执行以下操作:

1)确定输入的日期是否有效,如果有效,则返回一个对象:

2)JavaScript Date对象

3)以mySQL格式(YYYY-MM-DD)格式化的日期

4)以典型格式(MM-DD-YYYY)格式化的日期

最后我编写了自己的函数,使用Regex并可以处理YYYY-MM-DD,YYYY / MM / DD,MM-DD-YY,MM / DD / YY,MM-DD-YYYY或MM / DD / YYYY。

函数在对象中返回mySQL格式和常规格式的原因仅仅是为了方便起见。我的网络应用程序需要在字段中显示的典型格式以及在保存数据时发送到服务器的mysQL格式。

代码如下所示。我确信有很多方法可以优化代码,但为了便于阅读,我将其编写为部分内容。即使每次用户在日期字段中输入数据时它都被设置为运行,它也不会让任何事情陷入困境。希望这有助于某人!

1 个答案:

答案 0 :(得分:2)

更新: momentjs要好得多。

可以在此jsfiddle上看到代码和示例。

function interpretDate(stringDate){
    var mysqlF = "(\\d{4})[-/](\\d{1,2})[-/](\\d{1,2})";
    var dispF = "(\\d{1,2})[-/](\\d{1,2})[-/]((?:\\d{4})|(?:\\d{2}))";
    var dispNoYearF = "(\\d{1,2})[-/](\\d{1,2})";
    var dateFormats = "(^"+mysqlF+"$)|(^"+dispF+"$)|(^"+dispNoYearF+"$)";

    //Let's try to extract the data
    data = stringDate.match(dateFormats);
    var month = -1;
    var day = -1;
    var year = -1;

    //Check to see if the verification failed
    if (data == undefined){
        //Invalid date
        return {valid: false, date: null, mysqlDate:null, displayDate: ""};
    }

    //Extract the data based on the entry type
    if (data[1] != undefined){//YYYY-MM-DD
        month = parseInt(data[3]);
        day = parseInt(data[4]);
        year = parseInt(data[2]);
    }else if (data[5] != undefined){//MM-DD-YYYY or MM-DD-YY
        month = parseInt(data[6]);
        day = parseInt(data[7]);
        year = parseInt(data[8]);
        if (year < 100){
            var yearString = new String(new Date().getFullYear());
            year = parseInt(yearString.substr(0,2) + year);
        }
    }else if (data[9] != undefined){//MM-DD
        month = parseInt(data[10]);
        day = parseInt(data[11]);
        year = parseInt(new Date().getFullYear());
    }

    //If we are here, we have three numbers, let's see if they make a real date
    var extractedDate = new Date(year, month-1, day);
    if (extractedDate.getFullYear() != year || extractedDate.getDate() != day || extractedDate.getMonth() != (month-1)){
        return {valid: false, date: null, mysqlDate:null, displayDate: ""};
    }

    //We have a valid date, let's add front zeros
    var monthFixed = month;
    if (monthFixed < 10) monthFixed = "0"+monthFixed;
    var dayFixed = day;
    if (dayFixed < 10) dayFixed = "0"+dayFixed;

    //We are done
    return {valid: true, date: extractedDate, mysqlDate:year+"-"+monthFixed+"-"+dayFixed, displayDate: month+"/"+day+"/"+year};
}