Detailed description of JavaScript time formatting,

Source: Internet
Author: User

Detailed description of JavaScript time formatting,

Thanks to the JS format Date and Time JS code written by a senior, It is very powerful !!!

Preface:

Although js provides various methods to obtain different attributes of the time Date object, such as: getDate method | getDay method | getFullYear method | getHours method ...... but it does not provide a method like java for users to format the specified time object according to their own provided template (pattern), so they encapsulate a small method, just for your convenience -. -If you have good suggestions, please kindly advise.

Knowledge points used:

• Arguments: indicates the function being executed and the parameters used to call the function. It cannot be explicitly created. Although it has the length attribute and can be set in the "[]" syntax like an array, it is not an array.

• Typeof object: An operator that returns a string that represents the data type of an expression. There are six possibilities: "number," "string," "boolean," "object," "function," and "undefined .".

• Object. constructor: The function used to create an object. The object must be the name of the object or function. This attribute is not available for basic data.

• Exec method: run the search in the string in regular expression mode and return an array containing the search result. If no match is found, null is returned. Matching elements of the same type in the array are not repeated.

• Str. split (Rex | str): Splits a string into a substring and returns the result as a string array.

• Throw Error ('msg '): throws an Error with Message information. Throw can be followed by any expression.

• There are also some usage of for... in, the three-object operator, and substr, which are not mentioned and are relatively simple.

Code snippet:

/****** Js time and date formatting *** <br> * <p> * The template string adopts a rigorous format. If it exceeds the value, an exception is thrown, the format of each type can only appear once. For example, an exception is thrown in the format of yyyy-mm-yyyy * </p> * y-year length: 2/4 <br> * q-quarter length: 1 <br> * M-month length: 1 ~ 2 digits <br> * d-day length: 1 ~ 2-digit <br> * H-time length: 1 ~ 2-digit 24-hour, h: 12-hour <br> * m-Minute length: 1 ~ 2-digit <br> * s-second length: 1 ~ 2-digit <br> * S-millisecond length: fixed 1-digit * @ param {Date type object} date * @ param {String type template String} fmt * @ return formatted Date String * @ author lyt * blongs: http://www.cnblogs.com/liuyitian/ */function DateFormat (date, fmt) {if (arguments. length! = 2) // check the number of parameters throw Error ('invalid arguments length '); if (! Date | (typeof date! = 'Object') | (d. constructor! = Date) // parameter validity check throw Error (arguments [0] + ': the type is not 'date'); if (/H + /. test (fmt) & amp;/h + /. test (fmt) throw Error ("hour format Error, the same type can only appear once in a row! ");/* Template parameter verification, regular expression Verification Method */var verify = function (Rex) {var arr = new regexp(rexcmd.exe c (fmt ); // obtain the matching result array if (! Arr) // return ""; if (fmt. split (Rex ). length> 2) // multiple throw errors occur at intervals of the same type ("fmt Format Error: the same type can only appear once in a row! "); Return arr [0];}; /*** Replace the month, day, hour, minute, and second with a common match * @ param {object o attribute key} r * @ param {r corresponds to a regular object} rex **/ var common = function (r, rex) {if (len! = 1 & len! = 2) throw Error ("month format Error: M can only appear 1/2 times"); len = 2? Fmt = fmt. replace (rex, o [r]. length = 1? "0" + o [r]: o [r]): fmt = fmt. replace (rex, o [r]);} var o = {// data storage object "y +": date. getFullYear () + "", // year "q +": Math. floor (date. getMonth () + 3)/3), // quarter "M +": date. getMonth () + 1 + "", // month "d +": date. getDate () + "", // Day "H +": date. getHours () + "", // 24 "h +": date. getHours () + "", // 12 "m +": date. getMinutes () + "", // minute "s +": date. getSeconds () + "", // second "S +": date. getMilliseconds () // millisecond} For (var r in o) {var rex, len, temp; rex = new RegExp (r); temp = verify (rex); // match the obtained string len = temp. length; // length if (! Len | len = 0) continue; if (r = "y +") {if (len! = 2 & len! = 4) throw Error ("year format Error: y can only appear 2/4 times"); len = 2? Fmt = fmt. replace (rex, o [r]. substr (2, 3): fmt = fmt. replace (rex, o [r]);} else if (r = "q +") {if (len! = 1) throw Error ("quarterly format Error: q can only appear once"); fmt = fmt. replace (rex, o [r]);} else if (r = "h +") {if (len! = 1 & len! = 2) throw Error ("hour format Error: h can only appear 1/2 times"); var h = (o [r]> 12? O [r]-12: o [r]) + ""; len = 2? Fmt = fmt. replace (rex, h. length = 1? "0" + h: h): fmt = fmt. replace (rex, h);} else if (r = "S +") {if (len! = 1) throw Error ("millisecond format Error: S can only appear once"); fmt = fmt. replace (rex, o [r]);} else {// (r = "M +" | r = "d +" | r = "H +" | r = "m +" | | r = "s + ") common (r, rex) }}return fmt ;}

The following are some demos for your reference:

Console. log (DateFormat (new Date (), 'yyyy year q quarter M month dd Day HH hour m minute s second millisecond '));


Console. log (DateFormat (new Date (), 'yyyy year yy q quarter M month dd Day HH hour m minute s S millisecond '));


Console. log (DateFormat (new Date (), 'yyyy year q quarter M month dd Day Hh hour m minute s second millisecond '));


Console. log (DateFormat ("I am not a time object", 'yyyy year q quarter M month dd Day Hh hour m minute s S millisecond '));


Console. log (DateFormat (new Date (), 'yyyy year q quarter MMM month dd Day HH hour m minute s S millisecond '));

Other effects will not be listed one by one. If you are interested, you can copy the code and test it directly. If you have any bugs or need to optimize the code, please be generous.

I have explained the knowledge about JavaScript time formatting through the above content. I hope you will like it.

Articles you may be interested in:
  • Javascript formatting time and date function code revised edition
  • Summary of js formatting time and date functions
  • Code for formatting datetime data functions in js
  • Summary of time formatting in JS
  • Multiple methods for formatting js timestamps into date formats
  • Example of js formatting time and js formatting Timestamp
  • How to format the date and time using JavaScript and examples of custom formatting Functions
  • How to format a timestamp string as a time tag in a jsp page
  • Js formatting time Summary
  • Js time and date formatting and encapsulation Functions
  • How to format the amount, characters, and time in js

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.