天天看點

js日期時間校驗

/**
 * 日期校驗
 * @param date
 * @returns {Boolean}
 */
function isDate(date)  
{  
    var reg = date.match(/^(\d{4})(-|\/)(\d{2})\2(\d{2})$/);  
    if(reg==null)return false;  
    var d= new Date(reg[1], reg[3]-1, reg[4]);  
    return (d.getFullYear()==reg[1]&&(d.getMonth()+1)==reg[3]&&d.getDate()==reg[4]);  
}

/**
 * 日期時間校驗
 * @param date
 * @returns {Boolean}
 */
function isDateTime(dateTime)  
{  
    var reg = /^(\d{4})(-|\/)(\d{2})\2(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;  
    var r = dateTime.match(reg);
    if(r==null)return false;  
    var d= new Date(r[1],r[3]-1,r[4],r[5],r[6],r[7]);  
    return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]);  
}

/**
 * 時間校驗
 * @param str
 * @param second	是否有秒
 * @returns {Boolean}
 */
function isTime(str, second)  
{
    if (second == true)
    {
        var time = str.match(/^(\d{2}):(\d{2}):(\d{2})$/);  
        if (time == null) {alert('輸入的參數不是時間格式'); return false;}  
        if (time[1]>23 || time[2]>59 || time[3]>59)  
        {  
            alert("時間格式不對");  
            return false  
        }  
    }
    else
    {
        var time = str.match(/^(\d{2}):(\d{2})$/);  
        if (time == null) {alert('輸入的參數不是時間格式'); return false;}  
        if (time[1]>23 || time[2]>59)  
        {  
            alert("時間格式不對");  
            return false  
        }
    }
    return true;  
}