Summary of javascript time processing methods (recommended)

Source: Internet
Author: User
Preface in front-end Javascript development, you will often encounter the problem of processing the date and time. A lot of processing functions are often used to complete a simple Date and Time Display Effect. To speed up website development, You can encapsulate the main code in a single function and call it directly when necessary. The following describes some time processing classes summarized for you. You can call it directly when you need it. Preface

In front-end Javascript development, you often encounter the problem of processing the date and time, and often use a lot of processing functions to complete a simple Date and Time Display Effect. To speed up website development, You can encapsulate the main code in a single function and call it directly when necessary. The following describes some time processing classes summarized for you. You can call it directly when needed.

Var myDate = new Date (); myDate. getYear (); // obtain the current year (2 digits) myDate. getFullYear (); // obtain the complete year (4 digits, 1970 -????) MyDate. getMonth (); // obtain the current month (0-11, 0 represents January) myDate. getDate (); // obtain the current day (1-31) myDate. getDay (); // obtain the current day X (0-6, 0 represents Sunday) myDate. getTime (); // obtain the current time (milliseconds starting from 1970.1.1) myDate. getHours (); // obtain the current hour (0-23) myDate. getMinutes (); // get the current number of minutes (0-59) myDate. getSeconds (); // obtain the current number of seconds (0-59) myDate. getMilliseconds (); // get the current number of milliseconds (0-999) myDate. toLocaleDateString (); // obtain the current date var mytime = myDate. toLocaleTimeString (); // obtain the current time myDate. toLocaleStr Ing (); // obtain the Date and time script library method list Date. prototype. isLeapYear determines the Date of the leap year. prototype. format Date. prototype. dateAdd Date calculation Date. prototype. dateDiff compares the Date difference. prototype. toString Date to string Date. prototype. toArray Date is split into array Date. prototype. datePart obtains part of the Date information. prototype. maxDayOfDate is the maximum number of days in the month where the Date is located. prototype. weekNumOfYear judge the week of the year in which the date is located StringToDate string to date type IsValidDate verify date validity CheckDateTime complete date time check daysBetween date day difference js Code ://-- ----------------------------------------------- // Determine a leap year // ----------------------------------------------------- Date. prototype. isLeapYear = function () {return (0 = this. getYear () % 4 & (this. get year () % 100! = 0) | (this. getYear () % 400 = 0 )));} // ------------------------------------------------- // format YYYY/yyyy/YY indicates the year // MM/M month // W/w weeks // dd/d/D date // hh/HH/h/H time // mm/m minutes // ss/SS/s/S seconds // --------------------------------------------------------- Date. prototype. format = function (formatStr) {var str = formatStr; var Week = ['day', 'yi', '2', '3', '4', '5 ', '6']; str = str. replace (/yyyy | YYYY/, this. ge TFullYear (); str = str. replace (/yy | YY/, (this. getYear () % 100)> 9? (This. getYear () % 100 ). toString (): '0' + (this. getYear () % 100); str = str. replace (/MM/, this. getMonth ()> 9? This. getMonth (). toString (): '0' + this. getMonth (); str = str. replace (/M/g, this. getMonth (); 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 (); return str;} // + --------------------------------------------------- // | returns the date format of the two days difference: YYYY-MM-dd // + interval function daysBetween (DateOne, dateTwo) {var OneMonth = DateOne. substring (5, DateOne. lastIndexOf ('-'); var OneDay = DateOne. substring (DateOne. length, DateOne. lastIndexOf ('-') + 1); var OneYear = DateOne. substring (0, DateOne. indexOf ('-'); var TwoMonth = DateTwo. substring (5, DateTwo. lastIndexOf ('-'); var TwoDay = DateTwo. substring (DateTwo. length, DateTwo. lastIndexOf ('-') + 1); var TwoYear = DateTwo. substring (0, DateTwo. indexOf ('-'); var cha = (Date. parse (OneMonth + '/' + OneDay + '/' + OneYear)-Date. parse (TwoMonth + '/' + TwoDay + '/' + TwoYear)/86400000); ret Urn Math. abs (cha);} // + --------------------------------------------------- // | Date calculation // + ----------------------------------------------------- Date. prototype. dateAdd = function (strInterval, Number) {var dtTmp = this; switch (strInterval) {case's ': return new Date (Date. parse (dtTmp) + (1000 * Number); case 'N': return new Date (Date. parse (dtTmp) + (60000 * Number); case 'H': return new Date (Date. pa Rse (dtTmp) + (3600000 * Number); case 'D': return new Date (Date. parse (dtTmp) + (86400000 * Number); case 'W': return new Date (Date. parse (dtTmp) + (86400000*7) * Number); case 'q': return new Date (dtTmp. getFullYear (), (dtTmp. getMonth () + Number * 3, dtTmp. getDate (), dtTmp. getHours (), dtTmp. getMinutes (), dtTmp. getSeconds (); case 'M': return new Date (dtTmp. getFullYear (), (dtTmp. getMonth () + Nu Mber, dtTmp. getDate (), dtTmp. getHours (), dtTmp. getMinutes (), dtTmp. getSeconds (); case 'y': return new Date (dtTmp. getFullYear () + Number), dtTmp. getMonth (), dtTmp. getDate (), dtTmp. getHours (), dtTmp. getMinutes (), dtTmp. getSeconds () ;}/// + --------------------------------------------------- // | compare the dtEnd format with the Date format or the valid Date format string // + invalid Date. prototype. dat EDiff = function (strInterval, dtEnd) {var dtStart = this; if (typeof dtEnd = 'string ') // If the string is converted to the date type {dtEnd = StringToDate (dtEnd);} switch (strInterval) {case 's': return parseInt (dtEnd-dtStart)/1000 ); case 'N': return parseInt (dtEnd-dtStart)/60000); case 'H': return parseInt (dtEnd-dtStart)/3600000); case 'D ': return parseInt (dtEnd-dtStart)/86400000); case 'W': return par SeInt (dtEnd-dtStart)/(86400000*7); case 'M': return (dtEnd. getMonth () + 1) + (dtEnd. getFullYear ()-dtStart. getFullYear () * 12)-(dtStart. getMonth () + 1); case 'y': return dtEnd. getFullYear ()-dtStart. getFullYear () ;}/// + ----------------------------------------------------- // | Date output string, reload the system's toString method // + 1_date. prototype. toString = function (show Week) {var myDate = this; var str = myDate. toLocaleDateString (); if (showWeek) {var Week = ['day', 'yi', '2', '3', '4', '5 ', '6']; str + = 'Week' + Week [myDate. getDay ()];} return str;} // + --------------------------------------------------- // | date validity verification // | format: YYYY-MM-DD or YYYY/MM/DD // + ----------------------------------------------------- function IsValidDate (DateStr) {var sDate = DateStr. replace (/(^ \ s + | \ s + $ )/ G, ''); // remove spaces on both sides; if (sDate ='') return true; // if the format meets YYYY-(/) MM -(/) DD Or YYYY-(/) M-(/) D or YYYY-(/) MM -(/) D is replaced with ''// database, the valid date can be: YYYY-MM/DD (2003-3/21), the database will be automatically converted to the YYYY-MM-DD format var s = sDate. replace (/[\ d] {4, 4} [\-/] {1} [\ d] {1} [\-/] {1} [\ d] {1, 2} /g, ''); if (s ='') // The description format meets the YYYY-MM-DD or YYYY-M-DD or YYYY-M-D or YYYY-MM-D {var t = new Date (sDate. replace (/\-/g, '/'); var ar = sDate. split (/[-/:]/); if (Ar [0]! = T. getYear () | ar [1]! = T. getMonth () + 1 | ar [2]! = T. getDate () {// alert ('incorrect date format! Format: YYYY-MM-DD or YYYY/MM/DD. Pay attention to the leap year. '); Return false ;}} else {// alert (' incorrect date format! Format: YYYY-MM-DD or YYYY/MM/DD. Pay attention to the leap year. '); Return false;} return true;} // + --------------------------------------------------- // | Date and Time check // | format: YYYY-MM-DD HH: MM: SS // + ----------------------------------------------------- function CheckDateTime (str) {var reg =/^ (\ d +)-(\ d {1, 2})-(\ d {1 }) (\ d {1, 2}) :( \ d {1, 2}) :( \ d {1, 2}) $/; var r = str. match (reg); if (r = null) return false; r [2] = r [2]-1; var d = new Date (r [1], r [2], r [3], r [4], r [5], r [6 ]); If (d. getFullYear ()! = R [1]) return false; if (d. getMonth ()! = R [2]) return false; if (d. getDate ()! = R [3]) return false; if (d. getHours ()! = R [4]) return false; if (d. getMinutes ()! = R [5]) return false; if (d. getSeconds ()! = R [6]) return false; return true;} // + ----------------------------------------------------- // | splits the Date into an array // + seasonal Date. prototype. toArray = function () {var myDate = this; var myArray = Array (); myArray [0] = myDate. getFullYear (); myArray [1] = myDate. getMonth (); myArray [2] = myDate. getDate (); myArray [3] = myDate. getHours (); myArray [4] = myDate. getMinutes (); MyArray [5] = myDate. getSeconds (); return myArray ;} // + ------------------------------------------------- // | get date data // | the interval parameter indicates the data type. // | y, m, D, w, ww, week, h, n minutes, s, s/+ --------------------------------------------------- Date. prototype. datePart = function (interval) {var myDate = this; var partStr = ''; var Week = ['day', 'day', 'two', '3 ', '4', '5', '6']; switch (interval) {case 'y': partStr = myDate. GetFullYear (); break; case 'M': partStr = myDate. getMonth () + 1; break; case 'D': partStr = myDate. getDate (); break; case 'W': partStr = Week [myDate. getDay ()]; break; case 'ww ': partStr = myDate. weekNumOfYear (); break; case 'H': partStr = myDate. getHours (); break; case 'N': partStr = myDate. getMinutes (); break; case's ': partStr = myDate. getSeconds (); break;} return partStr;} // + ------------------------- ------------------------ // | Obtains the maximum number of days of the month in which the current Date is located. // + ------------------------------------------- Date. prototype. maxDayOfDate = function () {var myDate = this; var ary = myDate. toArray (); var date1 = (new Date (ary [0], ary [1] + 1,1); var date2 = date1.dateAdd (1, 'M', 1 ); var result = dateDiff (date1.Format ('yyyy-MM-dd'), date2.Format ('yyyy-MM-dd'); return result;} // + -------------------------------- ------------------- // | Obtain the week of the current Date in the year. // + ------------------------------------------------------- Date. prototype. weekNumOfYear = function () {var myDate = this; var ary = myDate. toArray (); var year = ary [0]; var month = ary [1] + 1; var day = ary [2]; document. write ('<script language = VBScript \> \ n'); document. write ('mydate = Datue (''+ month + '-' + day + '-' + year +'') \ n'); document. write ('result = DatePart (' Ww ', myDate) \ n'); document. write ('\ n'); return result ;} // + convert // | convert string to date type // | format: MM/dd/yyyy mm-dd-YYYY/MM/dd YYYY-MM-dd // + ----------------------------------- function stringToDate (DateStr) {var converted = Date. parse (DateStr); var myDate = new Date (converted); if (isNaN (myDate) {// var delimCahar = DateStr. indexOf ('/')! =-1? '/': '-'; Var arys = DateStr. split ('-'); myDate = new Date (arys [0], -- arys [1], arys [2]);} return myDate;} to display: current Date plus time (for example,) function CurentTime () {var now = new Date (); var year = now. getFullYear (); // year var month = now. getMonth () + 1; // month var day = now. getDate (); // var hh = now. getHours (); // var mm = now. getMinutes (); // minute var clock = year + "-"; if (month <10) clock + = "0"; clock + = month + "-"; if (day <10) clock + = "0"; clock + = day + ""; if (hh <10) clock + = "0 "; clock + = hh + ":"; if (mm <10) clock + = '0'; clock + = mm; return (clock );}

Summary

The above is the detailed content of the javascript time processing method summary (recommended). For more information, see other related articles in the first PHP community!

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.