字符串日期到javascript日期:解析日期 [英] String date to javascript date: Parse date

查看:687
本文介绍了字符串日期到javascript日期:解析日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to parse dates (string date format to javascript date format), but I have various string date format like YYYY-MM-DD, DD-MM-YYYY and 'DD/MM/YYYY' and so..

是否有任何通用程序或方法从这些字符串日期格式修改为javascript日期格式?

Is there any generic procedure or way to convent from these string date format to javascript date format?

推荐答案

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

这篇关于字符串日期到javascript日期:解析日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆