如何使用jquery支持01/01/2010和1/1/2010日期格式



我在表单中使用文本字段获取日期,我使用下面的jquery编码进行日期验证(mm/dd/yyyy)。

function isDate(txtDate) {
    var objDate,  // date object initialized from the txtDate string
        mSeconds, // txtDate in milliseconds
        day,      // day
        month,    // month
        year;     // year
    // date length should be 10 characters (no more no less)
    if (txtDate.length !== 10) {
        return false;
    }
    // third and sixth character should be '/'
    if (txtDate.substring(2, 3) !== '/' || txtDate.substring(5, 6) !== '/') {
        return false;
    }
    // extract month, day and year from the txtDate (expected format is mm/dd/yyyy)
    // subtraction will cast variables to integer implicitly (needed
    // for !== comparing)
    month = txtDate.substring(0, 2) - 1; // because months in JS start from 0
    day = txtDate.substring(3, 5) - 0;
    year = txtDate.substring(6, 10) - 0;
    // test year range
    if (year < 1000 || year > 3000) {
        return false;
    }
    // convert txtDate to milliseconds
    mSeconds = (new Date(year, month, day)).getTime();
    // initialize Date() object from calculated milliseconds
    objDate = new Date();
    objDate.setTime(mSeconds);
    // compare input date and parts from Date() object
    // if difference exists then date isn't valid
    if (objDate.getFullYear() !== year ||
        objDate.getMonth() !== month ||
        objDate.getDate() !== day) {
        return false;
    }
    // otherwise return true
    return true;
}

这适用于日期格式(mm/dd/yyyy)。。但是现在我需要支持像(m/d/yyyy)这样的格式。

我该怎么做?

经过这些修改后的示例将支持两种格式:

// date length should be between 8 and 10 characters (no more no less)
if (txtDate.length < 8 || txtDate.length > 10) {
    return false;
}
var tokens = txtDate.split('/');
// there should be exactly three tokens
if (tokens.length !== 3) {
    return false;
}
// extract month, day and year from the txtDate
month = parseInt(tokens[0]) - 1; // because months in JS start from 0
day = parseInt(tokens[1]);
year = parseInt(tokens[2]);

试试date.js库

有了它,你可以编写如下代码:

Date.parse('7/1/2004')          // Thu Jul 01 2004

Date.js中的所有解析都可以通过包含包含区域性信息的文件来全球化,所以您应该能够让它做您想做的事情。

你所要做的就是在你的页面中包含以下文件以开始:

<script type="text/javascript" src="date.js"></script>
<script type="text/javascript" src="date-de-DE.js"></script>

编辑

Date.js现在似乎已经过时了,但Moment.js看起来是一个不错的替代方案。

最新更新