2

我想解析日期(字符串日期格式为 javascript 日期格式),但我有各种字符串日期格式,如YYYY-MM-DD,DD-MM-YYYY等等'DD/MM/YYYY'..

是否有任何通用程序或方法可以将这些字符串日期格式转换为 javascript 日期格式?

4

4 回答 4

2

这是我使用的两个库:

于 2012-11-05T10:51:47.750 回答
1

这里userFormat的字符串可以是这些格式'DD-MM-YYYY''YYYY-MM-DD'等等'DD/MM/YYYY'

function parseDate(dateString, userFormat) {
    var delimiter, theFormat, theDate, month, date, year;
    // Set default format if userFormat is not provided
    userFormat = userFormat || 'yyyy-mm-dd';

    // Find custom delimiter by excluding
    // month, day and year characters
    delimiter = /[^dmy]/.exec(userFormat)[0];

    // Create an array with month, day and year
    // so we know the format order by index
    theFormat = userFormat.split(delimiter);

    //Create an array of dateString.
    theDate = dateString.split(delimiter);
    for (var i = 0, len = theDate.length; i < len; i++){
      //assigning values for date, month and year based on theFormat array.
      if (/d/.test(theFormat[i])){
        date = theDate[i];
      }
      else if (/m/.test(theFormat[i])){
        month = parseInt(theDate[i], 10) - 1;
      }
      else if (/y/.test(theFormat[i])){
        year = theDate[i];
      }
    }
    return (new Date(year, month, date));
}
于 2012-11-05T10:40:37.277 回答
0

去拿datejs。

http://www.datejs.com/

...再也不用为编写自己的 Javascript 日期函数而烦恼了。

于 2012-11-05T10:42:47.097 回答
-1
function dateParsing(toDate, dateFormat) {
    var dt = Date.parseInvariant(todate, dateFormat); // pass date and your desired format e.g yyyy/M/dd            
    alert(dt); // to check date
}
于 2012-11-05T11:46:53.720 回答