javascript中對Date類型的常用操作

來源:互聯網
上載者:User

 

 /** * 日期時間指令碼庫方法列表: * (1)Date.isValiDate:日期合法性驗證 * (2)Date.isValiTime:時間合法性驗證 * (3)Date.isValiDateTime:日期和時間合法性驗證 * (4)Date.prototype.isLeapYear:判斷是否閏年 * (5)Date.prototype.format:日期格式化 * (6)Date.stringToDate:字串轉成日期類型 * (7)Date.daysBetween:計算兩個日期的天數差 * (8)Date.prototype.dateAdd:日期計算,支援正負數 * (9)Date.prototype.dateDiff:比較日期差:比較兩個時期相同的欄位,返回相差值 * (10)Date.prototype.toArray:把日期分割成數組:按數組序號分別為:年月日時分秒 * (11)Date.prototype.datePart:取得日期資料資訊 *//** * 日期合法性驗證:判斷dataStr是否符合formatStr指定的日期格式 * 樣本: * (1)alert(Date.isValiDate('2008-02-29','yyyy-MM-dd'));//true * (2)alert(Date.isValiDate('aaaa-58-29','yyyy-MM-dd'));//false * dateStr:必選,日期文字 * formatStr:可選,格式字串,可選格式有:(1)yyyy-MM-dd(預設格式)或YYYY-MM-DD (2)yyyy/MM/dd或YYYY/MM/DD (3)MM-dd-yyyy或MM-DD-YYYY (4)MM/dd/yyyy或MM/DD/YYYY */Date.isValiDate = function(dateStr, formatStr){    if(!dateStr){        return false;    }    if(!formatStr){        formatStr = "yyyy-MM-dd";//預設格式:yyyy-MM-dd    }    if(dateStr.length!=formatStr.length){        return false;    }else{        if(formatStr=="yyyy-MM-dd"||formatStr=="YYYY-MM-DD"){            var r1=/^(((((([02468][048])|([13579][26]))(00))|(\d{2}(([02468][48])|([13579][26]))))\-((((0[13578])|(1[02]))\-(([0-2][0-9])|(3[01])))|(((0[469])|(11))\-(([0-2][0-9])|(30)))|(02\-([0-2][0-9]))))|(\d{2}(([02468][1235679])|([13579][01345789]))\-((((0[13578])|(1[02]))\-(([0-2][0-9])|(3[01])))|(((0[469])|(11))\-(([0-2][0-9])|(30)))|(02\-(([0-1][0-9])|(2[0-8]))))))$/;            return r1.test(dateStr);        }else if(formatStr=="yyyy/MM/dd"||formatStr=="YYYY/MM/DD"){            var r2=/^(((((([02468][048])|([13579][26]))(00))|(\d{2}(([02468][48])|([13579][26]))))\/((((0[13578])|(1[02]))\/(([0-2][0-9])|(3[01])))|(((0[469])|(11))\/(([0-2][0-9])|(30)))|(02\/([0-2][0-9]))))|(\d{2}(([02468][1235679])|([13579][01345789]))\/((((0[13578])|(1[02]))\/(([0-2][0-9])|(3[01])))|(((0[469])|(11))\/(([0-2][0-9])|(30)))|(02\/(([0-1][0-9])|(2[0-8]))))))$/;            return r2.test(dateStr);        }else if(formatStr=="MM-dd-yyyy"||formatStr=="MM-DD-YYYY"){            var r3=/^((((((0[13578])|(1[02]))\-(([0-2][0-9])|(3[01])))|(((0[469])|(11))\-(([0-2][0-9])|(30)))|(02\-([0-2][0-9])))\-(((([02468][048])|([13579][26]))(00))|(\d{2}(([02468][48])|([13579][26])))))|(((((0[13578])|(1[02]))\-(([0-2][0-9])|(3[01])))|(((0[469])|(11))\-(([0-2][0-9])|(30)))|(02\-(([0-1][0-9])|(2[0-8])))))\-\d{2}(([02468][1235679])|([13579][01345789])))$/;            return r3.test(dateStr);        }else if(formatStr=="MM/dd/yyyy"||formatStr=="MM/DD/YYYY"){            var r4=/^((((((0[13578])|(1[02]))\/(([0-2][0-9])|(3[01])))|(((0[469])|(11))\/(([0-2][0-9])|(30)))|(02\/([0-2][0-9])))\/(((([02468][048])|([13579][26]))(00))|(\d{2}(([02468][48])|([13579][26])))))|(((((0[13578])|(1[02]))\/(([0-2][0-9])|(3[01])))|(((0[469])|(11))\/(([0-2][0-9])|(30)))|(02\/(([0-1][0-9])|(2[0-8])))))\/\d{2}(([02468][1235679])|([13579][01345789])))$/;            return r4.test(dateStr);        }else{            alert("日期格式不正確!");            return false;        }    }    return false;}/** * 時間合法性驗證:判斷timeStr是否符合formatStr指定的時間格式 * 樣本: * (1)alert(Date.isValiTime('23:59:59','hh:mm:ss'));//true * (2)alert(Date.isValiTime('24-68-89','hh:mm:ss'));//false * timeStr:必選,日期文字 * formatStr:可選,格式字串,可選格式有:(1)hh:mm:ss(預設格式) (2)hh-mm-ss (3)hh/mm/ss */Date.isValiTime = function(timeStr, formatStr){    if(!timeStr){        return false;    }    if(!formatStr){        formatStr = "hh:mm:ss";//預設格式:hh:mm:ss    }    if(timeStr.length!=formatStr.length){        return false;    }else{        if(formatStr=="hh:mm:ss"){            var r1=/^(([0-1][0-9])|(2[0-3]))\:([0-5][0-9])\:([0-5][0-9])$/;            return r1.test(timeStr);        }else if(formatStr=="hh-mm-ss"){            var r2=/^(([0-1][0-9])|(2[0-3]))\-([0-5][0-9])\-([0-5][0-9])$/;            return r2.test(timeStr);        }else if(formatStr=="hh/mm/ss"){            var r3=/^(([0-1][0-9])|(2[0-3]))\/([0-5][0-9])\/([0-5][0-9])$/;            return r3.test(timeStr);        }else{            alert("時間格式不正確!");            return false;        }    }    return false;}/** * 日期和時間合法性驗證 * 格式:yyyy-MM-dd hh:mm:ss */Date.isValiDateTime = function(dateTimeStr){    var dateTimeReg=/^(((((([02468][048])|([13579][26]))(00))|(\d{2}(([02468][48])|([13579][26]))))\-((((0[13578])|(1[02]))\-(([0-2][0-9])|(3[01])))|(((0[469])|(11))\-(([0-2][0-9])|(30)))|(02\-([0-2][0-9]))))|(\d{2}(([02468][1235679])|([13579][01345789]))\-((((0[13578])|(1[02]))\-(([0-2][0-9])|(3[01])))|(((0[469])|(11))\-(([0-2][0-9])|(30)))|(02\-(([0-1][0-9])|(2[0-8]))))))(\s{1}(([0-1][0-9])|(2[0-3]))\:([0-5][0-9])\:([0-5][0-9]))?$/    return dateTimeReg.test(dateTimeStr);}/** * 判斷閏年 :一般規律為:四年一閏,百年不閏,四百年再閏。 */Date.prototype.isLeapYear = function(){    return (this.getYear()%4==0&&((this.getYear()%100!=0)||(this.getYear()%400==0)));}/** * 日期格式化: * formatStr:可選,格式字串,預設格式:yyyy-MM-dd hh:mm:ss * 約定如下格式: * (1)YYYY/yyyy/YY/yy 表示年份 * (2)MM/M 月份 * (3)W/w 星期 * (4)dd/DD/d/D 日期 * (5)hh/HH/h/H 時間 * (6)mm/m 分鐘 * (7)ss/SS/s/S 秒 * (8)iii 毫秒 */Date.prototype.format = function(formatStr){    var str = formatStr;    if(!formatStr){        str = "yyyy-MM-dd hh:mm:ss";//預設格式    }    var Week = ['日','一','二','三','四','五','六'];        str=str.replace(/yyyy|YYYY/,this.getFullYear());    str=str.replace(/yy|YY/,(this.getYear() % 100)>9?(this.getYear() % 100).toString():'0' + (this.getYear() % 100));        str=str.replace(/MM/,this.getMonth()>=9?(parseInt(this.getMonth())+1).toString():'0' + (parseInt(this.getMonth())+1));    str=str.replace(/M/g,(parseInt(this.getMonth())+1));        str=str.replace(/w|W/g,Week[this.getDay()]);        str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():'0' + this.getDate());    str=str.replace(/d|D/g,this.getDate());        str=str.replace(/hh|HH/,this.getHours()>9?this.getHours().toString():'0' + this.getHours());    str=str.replace(/h|H/g,this.getHours());    str=str.replace(/mm/,this.getMinutes()>9?this.getMinutes().toString():'0' + this.getMinutes());    str=str.replace(/m/g,this.getMinutes());        str=str.replace(/ss|SS/,this.getSeconds()>9?this.getSeconds().toString():'0' + this.getSeconds());    str=str.replace(/s|S/g,this.getSeconds());        str=str.replace(/iii/g,this.getMilliseconds()<10?'00'+this.getMilliseconds():(this.getMilliseconds()<100?'0'+this.getMilliseconds():this.getMilliseconds()));        return str;}/** * 字串轉成日期類型: * dateStr:必選,日期文字,如果無法解析成日期類型,返回null * 格式: * (1)yyyy/MM/dd:IE和FF通用 * (2)MM/dd/yyyy:IE和FF通用 * (3)MM-dd-yyyy:僅IE * (4)yyyy-MM-dd:非IE,且時鐘被解析在8點整 */Date.stringToDate = function(dateStr){    if(!dateStr){        alert("字串無法解析為日期");        return null;    }else{        if(Date.isValiDate(dateStr,"yyyy/MM/dd")||Date.isValiDate(dateStr,"MM/dd/yyyy")){            return new Date(Date.parse(dateStr));        }else{            if((!-[1,])){//IE                if(Date.isValiDate(dateStr,"MM-dd-yyyy")){                    return new Date(Date.parse(dateStr));                }else{                    alert("字串無法解析為日期");                    return null;                }            }else{//非IE                if(Date.isValiDate(dateStr,"yyyy-MM-dd")){                    return new Date(Date.parse(dateStr));                }else{                    alert("字串無法解析為日期");                    return null;                }            }        }    }    return null;}/** * 計算兩個日期的天數差: * dateOne:必選,必須是Data類型的執行個體 * dateTwo:必選,必須是Data類型的執行個體 */Date.daysBetween = function(dateOne,dateTwo){    if((dateOne instanceof Date)==false||(dateTwo instanceof Date)==false){        return 0;    }else{        return Math.abs(Math.floor((dateOne.getTime()-dateTwo.getTime())/1000/60/60/24));    }}/** * 日期計算:支援負數,即可加可減,返回計算後的日期 * num:必選,必須是數字,且正數是時期加,負數是日期減 * field:可選,標識是在哪個欄位上進行相加或相減,欄位見如下的約定。無此參數時,預設為d * 約定如下格式: * (1)Y/y 年 * (2)M 月 * (3)W/w 周 * (4)D/d 日 * (5)H/h 時 * (6)m 分 * (7)S/s 秒 * (8)Q/q 季 */Date.prototype.dateAdd = function(num, field){    if((!num)||isNaN(num)||parseInt(num)==0){        return this;    }    if(!field){        field = "d";    }    switch(field){        case 'Y':        case 'y':return new Date((this.getFullYear()+num), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds());break;        case 'Q':        case 'q':return new Date(this.getFullYear(), (this.getMonth()+num*3), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds());break;        case 'M':return new Date(this.getFullYear(), this.getMonth()+num, this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds());break;        case 'W':        case 'w':return new Date(Date.parse(this) + ((86400000 * 7) * num));break;        case 'D':        case 'd':return new Date(Date.parse(this) + (86400000 * num));break;        case 'H':        case 'h':return new Date(Date.parse(this) + (3600000 * num));break;        case 'm':return new Date(Date.parse(this) + (60000 * num));break;        case 'S':        case 's':return new Date(Date.parse(this) + (1000 * num));break;        default: return this;    }    return this;}/** * 比較日期差:比較兩個時期相同的欄位,返回相差值 * dtEnd:必選,必須是Data類型的執行個體 * field:可選,標識是在哪個欄位上進行比較,欄位見如下的約定。無此參數時,預設為d * 約定如下格式: * (1)Y/y 年 * (2)M 月 * (3)W/w 周 * (4)D/d 日 * (5)H/h 時 * (6)m 分 * (7)S/s 秒 */Date.prototype.dateDiff = function(dtEnd, field){    var dtStart = this;    if((dtEnd instanceof Date)==false){        return 0;    }else{        if(!field){            field = "d";        }        switch(field){            case 'Y':            case 'y':return dtEnd.getFullYear() - dtStart.getFullYear();break;            case 'M':return (dtEnd.getMonth()+1)+((dtEnd.getFullYear()-dtStart.getFullYear())*12) - (dtStart.getMonth()+1);break;            case 'W':            case 'w':return parseInt((dtEnd - dtStart) / (86400000 * 7));break;            case 'D':            case 'd':return parseInt((dtEnd - dtStart) / 86400000);break;            case 'H':            case 'h':return parseInt((dtEnd - dtStart) / 3600000);break;            case 'm':return parseInt((dtEnd - dtStart) / 60000);break;            case 'S':            case 's':return parseInt((dtEnd - dtStart) / 1000);break;            default: return 0;        }        return 0;    }}/** * 把日期分割成數組:按數組序號分別為:年月日時分秒 */Date.prototype.toArray = function(){    var myArray = new Array();    myArray[0] = this.getFullYear();    myArray[1] = this.getMonth();    myArray[2] = this.getDate();    myArray[3] = this.getHours();    myArray[4] = this.getMinutes();    myArray[5] = this.getSeconds();    return myArray;}/** * 取得日期資料資訊: * field:可選,標識是在哪個欄位上進行比較,欄位見如下的約定。無此參數時,預設為d * (1)Y/y 年 * (2)M 月 * (3)W/w 周 * (4)D/d 日 * (5)H/h 時 * (6)m 分 * (7)S/s 秒 */Date.prototype.datePart = function(field){    if(!field){        field = "d";    }    var Week = ['日','一','二','三','四','五','六'];    switch (field){        case 'Y' :        case 'y' :return this.getFullYear();break;        case 'M' :return (this.getMonth()+1);break;        case 'W' :        case 'w' :return Week[this.getDay()];break;        case 'D' :        case 'd' :return this.getDate();break;        case 'H' :        case 'h' :return this.getHours();break;        case 'm' :return this.getMinutes();break;        case 's' :return this.getSeconds();break;        default:return this.getDate();    }    return this.getDate();}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.