且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

字符串日期到javascript日期:解析日期

更新时间:2022-01-02 05:06:30

此处 userFormat 字符串可以采用以下格式'DD-MM-YYYY''YYYY-MM- DD''DD / MM / YYYY'等..

Here userFormat string could be in these format 'DD-MM-YYYY', 'YYYY-MM-DD', 'DD/MM/YYYY' etc..

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));
}