Prototype method extension for JavaScript date

Source: Internet
Author: User

In JavaScript development, it is often necessary to do a variety of validation or formatting of the date type of object, but JS does not provide so many such fine functions, so we have to use prototype expansion, the following is my own implementation of the date type common operation method, You can save it as a date.js and then call it in the program. Lanxi County Quwan Home Photography

/** * Date Time Script Library method list: * (1) Date.isvalidate: Date Legitimacy Verification * (2) Date.isvalitime: Time Validity Verification * (3) Date.isvalidatetime: Date and time validity verification * (4) Date.prototype.isLeapYear: Judging if leap year * (5) Date.prototype.format: Date formatting * (6) Date.stringtodate: string to date type * (7) Date.daysbetween: Calculates the difference of days for two dates * (8) DATE.PROTOTYPE.DATEADD: Date calculation, positive negative numbers supported * (9) Date.prototype.dateDiff: comparison Date difference: Compare two periods of the same field, return the difference value * (TEN) Date.prototype.toArray: Divide the date into the array: by the number of the arrays: month and day time and minute (one) Date.prototype.datePart: Obtain date data information *//** * Date legitimacy verification: Determine if the datastr conforms to the date format specified by FORMATSTR * Example: * (1) alert (date.isvalidate (' 2008-02-29 ', ' yyyy-mm-dd '));//true * (2) alert (date.isvalidate (' aaaa-58-29 ', ' yyyy-mm-dd '));//false * Datestr: Required, Date String * formatstr: Optional, format string, optional format: (1) YYYY-MM-DD (default format) or YYYY-MM-DD (2) Yyyy/mm/dd or YYYY/MM/DD (3) mm-dd-yyyy or mm-dd-yyyy (    4) mm/dd/yyyy or mm/dd/yyyy */date.isvalidate = function (Datestr, formatstr) {if (!DATESTR) {return false;        if (!formatstr) {formatstr = "yyyy-mm-dd";//Default format: Yyyy-mm-dd} if (datestr.length!=formatstr.length) {    return false; }else{if (formatstr== "Yyyy-mm-dd" | | [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" | | [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 ("date format is incorrect!)            ");        return false; }} return false;} /** * Time Legitimacy verification: judging TimESTR conforms to FORMATSTR specified time format * Example: * (1) alert (date.isvalitime (' 23:59:59 ', ' hh:mm:ss ')),//true * (2) alert (Date.isvalitime ( ' 24-68-89 ', ' hh:mm:ss ');//false * Timestr: Required, date String * formatstr: Optional, format string, optional format: (1) HH:MM:SS (default format) (2) Hh-mm-ss (3) hh/mm    /ss */date.isvalitime = function (Timestr, formatstr) {if (!TIMESTR) {return false; if (!formatstr) {formatstr = "hh:mm:ss";//Default format: Hh:mm:ss} if (timestr.length!=formatstr.length) {RE    Turn 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 ("The time format is incorrect!            ");        return false; }} RETurn false;} /** * Date and time legitimacy verification * Format: 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);} /** * Judgment Leap Year: The general rule is: four years a leap, a century does not leap, 400 years and then leap. */date.prototype.isleapyear = function () {return (This.getyear ()%4==0&& ((This.getyear () 0!=0) | | (This.getyear ()%400==0)));} /** * Date Formatting: * formatstr: Optional, format string, default format: YYYY-MM-DD HH:MM:SS * Convention Format: * (1) yyyy/yyyy/yy/yy for Year * (2) mm/m month * (3) w/w Week *     (4) dd/dd/d/d date * (5) hh/hh/h/h time * (6) mm/m minutes * (7) ss/ss/s/s seconds * (8) III Milliseconds */date.prototype.format = function (formatstr) { var str = Formatstr;        if (!formatstr) {str = "yyyy-mm-dd hh:mm:ss";//Default format} var Week = [' Day ', ' one ', ' two ', ' three ', ' four ', ' five ', ' six ']; Str=str.replace (/yyyy|    Yyyy/,this.getfullyear ()); Str=str.replace (/yy| yy/, (this.getyear ()%) >9?        (This.getyear ()%). 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? ' +this.getmilliseconds ():(this.getmilliseconds () <100? '        0 ' +this.getmilliseconds (): This.getmilliseconds ())); return str;} /** * String to date type: * DATESTR: Required, date string, if unable to resolve to date type, return NULL * format: * (1) Yyyy/mm/dd:ie and FF Universal * (2) Mm/dd/yyyy:ie and FF Universal * (3) Mm-dd-yy YY: IE only * (4) YYYY-MM-DD: Non ie, and the clock is parsed at 8 o'clock full */date.stringtodate = function (datestr) {if (!DATESTR) {alert ("string cannot be resolved to date")        ;    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 NE                W Date (Date.parse (DATESTR));                    }else{alert ("String cannot be resolved to date");                return null;           } }else{//Non-IE if (date.isvalidate (Datestr, "Yyyy-mm-dd")) {return new Date (Date.parse (DateS                TR));                    }else{alert ("String cannot be resolved to date");                return null; }}}} return null;} /** * Calculates the difference of days for two dates: * Dateone: Required, must be an instance of data type * Datetwo: required, must be an instance of data type */date.daysbetween = function (dateone,datetwo) {i F ((Dateone instanceof Date) ==false| |    (Datetwo instanceof Date) ==false) {return 0;    }else{return Math.Abs (Math.floor (Dateone.gettime ()-datetwo.gettime ())); }}/** * Date Calculation: Support negative numbers, can be added and subtracted, return the calculated date * num: Required, must be a number, and positive is the period plus, negative is the date minus * field: optional, the identification is in which field to add or subtract, the field see the following convention. Without this parameter, the default is D * convention in the following format: * (1) y/y Year * (2) M month * (3) w/w Week * (4) d/d Day * (5) h/h * (6) M * (7) s/s seconds * (8) q/q season */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 (), th        Is.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));        Case ' d ': Case ' d ': return new Date (Date.parse (this) + (86400000 * num));        Case ' h ': Case ' h ': return new Date (Date.parse (this) + (3600000 * num));        Case ' m ': return new Date (Date.parse (this) + (60000 * num));        Case ' s ': Case's ': Return new Date (Date.parse (this) + (* num));    Default:return this; } return this; /** * Comparison Date difference: Compare two periods of the same field, return a difference value * DtENd: Required, must be an instance of data type * field: Optional, identifies the field on which to compare, and the field is shown in the following convention. Without this parameter, the default is D * convention in the following format: * (1) y/y Year * (2) M month * (3) w/w Week * (4) d/d Day * (5) h/h * (6) M * (7) s/s seconds */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 (); 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));            Case ' d ': Case ' d ': Return parseint ((dtend-dtstart)/86400000);            Case ' h ': Case ' h ': Return parseint ((dtend-dtstart)/3600000);            Case ' m ': Return parseint ((Dtend-dtstart)/60000); Case ' s ': Case ' s ': Return parseInt ((Dtend-dtstart)/+);        Default:return 0;    } return 0;    }}/** * Divide the date into groups: by array ordinal: Month day time seconds */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;} /** * Get Date data information: * Field: Optional, identifies the field on which to compare, the field is shown in the following convention. Without this parameter, the default is D * (1) y/y years * (2) M months * (3) w/w weeks * (4) d/d days * (5) h/h * (6) M * (7) s/s seconds */date.prototype.datepart = function (f    Ield) {if (!field) {field = "D";    } var Week = [' Day ', ' one ', ' two ', ' three ', ' four ', ' five ', ' six '];        Switch (field) {case ' Y ': Case ' y ': return this.getfullyear ();        Case ' M ': Return (This.getmonth () +1);        Case ' W ': Case ' W ': Return Week[this.getday ()];break;        Case ' d ': Case ' d ': return This.getdate (); Case ' h ': Case ' h ': return thIs.gethours (); break;        Case ' m ': return This.getminutes ();        Case ' s ': return This.getseconds ();    Default:return this.getdate (); } return This.getdate ();}

Prototype method extension for JavaScript date

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.