JS date Format Function Performance Optimization Chapter

Source: Internet
Author: User
Tags dateformat

A log function is required in the recently developed software, and one of the important functions is to display the date and time. So on-line search, search for a large number of date formatting functions, but compared, feel code is not elegant, and performance is not to force.
Some of the code on the line is evaluated, here are some conclusions and optimization code.

The test code is as follows, in the same browser, the Format function is calculated 500,000 times:

var New Date (). GetTime (); var New Date ();  for (var i = 0;i<500000;i++) {    date.format1 (' yyyy-mm-dd hh:mm:ss ');} Console.log (new Date (). GetTime ()-start);

Function 1:

//An extension to date that converts date to a string of the specified format//the Month (m), Day (d), hour (h), Minute (m), second (s), quarter (q) can be used with 1-2 placeholders,//year (Y) can use 1-4 placeholders, milliseconds (S) with only 1 placeholders (1-3 digits)//Example://(New Date ()). Format ("Yyyy-mm-dd hh:mm:ss. S ") ==> 2006-07-02 08:09:04.423//(New Date ()). Format ("yyyy-m-d h:m:s.s") ==> 2006-7-2 8:9:4.18DATE.PROTOTYPE.FORMAT1 =function(FMT) {//Author:meizz    varo = {        "m+": This. GetMonth () + 1,//Month"D+": This. GetDate (),//Day"H +": This. GetHours (),//hours"m+": This. getminutes (),//points"S+": This. getseconds (),//seconds"q+": Math.floor (( This. GetMonth () + 3)/3),//Quarterly"S": This. Getmilliseconds ()//milliseconds    }; if(/(y+)/.test (FMT)) FMT = Fmt.replace (regexp.$1, ( This. getFullYear () + ""). substr (4-regexp.$1. length));  for(varKincho)if(NewRegExp ("(" + K + ")"). Test (FMT)) FMT = Fmt.replace (regexp.$1, (regexp.$1.length = = 1)? (O[k]): (("XX" + o[k]). substr ("" +o[k])); returnFMT;}

Test three times:

Score 1:6,657 MS score 2:6,739 MS score 3:6,747 msec average: 6714 ms

Function 2:

/** * For the extension of date, the date is converted to a specified format of string * months (M), Day (d), 12 hours (h), 24 hours (h), minutes (m), seconds (s), Weeks (E), quarter (q) can be used with 1-2 placeholders * year (y) can use 1-4 placeholders , milliseconds (S) can only be used with 1 placeholders (1-3 digits) * Eg: * (new Date ()). Pattern ("Yyyy-mm-dd hh:mm:ss.       S ") ==> 2006-07-02 08:09:04.423 * (New Date ()). Pattern (" Yyyy-mm-dd E HH:mm:ss ") ==> 2009-03-10 II 20:09:04 * (new Date ()). Pattern ("Yyyy-mm-dd EE hh:mm:ss") ==> 2009-03-10 Tuesday 08:09:04 * (new Date ()). Pattern ("Yyyy-mm-dd E       EE hh:mm:ss ") ==> 2009-03-10 Tuesday 08:09:04 * (New Date ()). Pattern (" yyyy-m-d h:m:s.s ") ==> 2006-7-2 8:9:4.18 */DATE.PROTOTYPE.FORMAT2=function(FMT) {varo = {             "m+": This. GetMonth () +1,//Month"D+": This. GetDate (),//Day"H +": This. getHours ()%12 = = 0? 12: This. GetHours ()%12,//hours"H +": This. GetHours (),//hours"m+": This. getminutes (),//points"S+": This. getseconds (),//seconds"q+": Math.floor (( This. GetMonth () +3)/3),//Quarterly "S": This. Getmilliseconds ()//milliseconds    }; varWeek = {             "0": "/u65e5",             "1": "/u4e00",             "2": "/u4e8c",             "3": "/u4e09",             "4": "/u56db",             "5": "/u4e94",             "6": "/U516D"            }; if(/(y+)/. Test (FMT)) {FMT=fmt.replace (Regexp.$1, ( This. getFullYear () + ""). substr (4-regexp.$1. length)); }             if(/(e+)/. Test (FMT)) {FMT=fmt.replace (regexp.$1, (regexp.$1.length>1)? (regexp.$1.length>2?) "/u661f/u671f": "/u5468"): "") +week[ This. GetDay () + ""]); }              for(varKincho) {                 if(NewRegExp ("(" + K + ")"). Test (FMT)) {FMT= Fmt.replace (regexp.$1, (regexp.$1.length==1)? (O[k]): (("XX" + o[k]). substr ("" +o[k])); }             }             returnFMT; } 

Test three times:

Score 1:7,334 MS score 2:7,497 MS score 3:7,498 msec average: 7443 ms

In a perfectionist attitude, I have re-created a better wheel, to share to the students in need, the code is as follows:

/** * Format dates, * @param date to format * @param format formatted pattern String * Supported pattern letters are: * y: Year, * M: Month of the Year (1-12), * d: Day of the Month (1-31), * H: Hours (0-23), * m: Min (0-59), * s: S (0-59), * s: msec (0-999), * Q: Quarter (1-4) * @return String * @author [email protected]*/functionDateFormat (date, format) {if(format = = =undefined) {Format=date; Date=NewDate (); }    varMap = {        "M": Date.getmonth () + 1,//Month"D": date.getdate (),//Day"H": date.gethours (),//hours"M": date.getminutes (),//points"S": Date.getseconds (),//seconds"Q": Math.floor ((Date.getmonth () + 3)/3),//Quarterly"S": Date.getmilliseconds ()//milliseconds    }; Format= Format.replace (/([YMDHMSQS]) +/g,function(all, t) {varv =Map[t]; if(v!==undefined) {            if(All.length > 1) {v= ' 0 ' +v; V= V.substr (v.length-2); }            returnv; }        Else if(t = = = ' Y '){            return(Date.getfullyear () + "). substr (4-all.length); }        returnAll ;    }); returnformat;}

How to use:

DateFormat (' Yyyy-mm-dd hh:mm:ss ');d Ateformat (new Date (), ' Yyyy-mm-dd hh:mm:ss ');
Test three times:
Score 1:2,903 MS score 2:2,900 MS score 3:2,896 msec average: 2899 ms

JS date Format Function Performance Optimization Chapter

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.