更新: 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};
}