JS time format

Source: Internet
Author: User
Tags dateformat throw exception time and date

Objective:

  JS provides a variety of different property methods for acquiring time date objects, such as: GetDate method | GetDay Method | getFullYear Method | GetHours method ... And so on, but did not provide a method like Java for users to format the specified time object according to their own template (pattern), so they encapsulated a small method, just for everyone to tease-.-, there are good suggestions also look generous to recommend Oh.

Use the knowledge point:

  • Arguments: The object represents the function being executed and the parameters of the function that called it.   It is not explicitly created, although it has the length property and can be evaluated in the same way as an array with the "[]" syntax , but it is not an array.
  • typeof The object : operator that returns a string that represents the data type of the expression. Six possible: "Number," "String," "Boolean," "Object," "function," and "undefined."
  • Object.constructor: Represents the function that created the object. The object must be the name of the objects or functions . The underlying data does not have this attribute.
  • Exec Method : Runs a lookup in a string with a regular expression pattern and returns an array containing the results of the lookup. If no match is found, it returns null. The same type of matching elements in the array does not recur .
  • str.split (REX|STR): Splits a string into substrings with a regular object or substring , and then takes the result as an array of strings Return.
  • Throw error (' msg '): throws an error with message information. The throw can be followed by any expression .
  • There are some for. In usage, trinocular operator, substr these will not be said, relatively simple.

Code Snippet:

/** * ***js time and date formatting * * * * <br> * <p> * template string in strict format, out of the exception will be thrown, and each class format can only appear once, such as: yyyy-mm-yyyy format will throw exception * </p> * y-year LENGTH:2/4 <br> * Q-quarter length:1 bit <br> * M-month length:1~2 bit <br> * D-day length:1~2 bit <br& Gt * H-time length:1~2 24-hour, h:12-hour <br> * m-min length:1~2 bit <br> * S-SEC length:1~2 bit <br> * S-ms Len GTH: Fixed 1-bit * @param {Date type Object} Date * @param {String type template string} FMT * @return formatted date string * @author Lyt * blongs:http://www.c nblogs.com/liuyitian/*/functionDateFormat (date, FMT) {if(Arguments.length! = 2)//parameter Count check        ThrowError (' arguments length not valid '); if(!date | | (typeofDate! = ' object ') | | (D.constructor! = Date))//parameter legality check        ThrowError (Arguments[0] + ': type is not a date type '); if(/h+/.test (FMT) &&/h+/. Test (FMT))ThrowError ("The hour format is wrong, the same type can only appear consecutively!") "); /*template parameter checking, regular verification method*/    varVerify =function(Rex) {vararr =NewREGEXP (Rex). EXEC (FMT);//get an array of matching results        if(!arr)//match failed to return            return""; if(Fmt.split (REX). length > 2)//multiple occurrences of the same type interval            ThrowError ("FMT Malformed: Only one occurrence of the same type! "); returnArr[0];    }; /** * Provide month, day, hours, minutes, seconds generic match replace * @param {object O property key} R * @param {R corresponds to regular object} Rex **/    varCommon =function(R, Rex) {if(Len!=1 && len!=2)            ThrowError ("Bad month format: 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]); }        varo = {//Data Storage Objects"y+": date.getfullyear () + "",//years"q+": Math.floor ((Date.getmonth () + 3)/3),//Quarterly"m+": Date.getmonth () + 1 + "",//Month"D+": date.getdate () + "",//Day"H +": date.gethours () + "",//24 O'Clock"H +": date.gethours () + "",//12 O'Clock"m+": date.getminutes () + "",//points"S+": date.getseconds () + "",//seconds"S+": Date.getmilliseconds ()//milliseconds    }             for(varRincho) {varrex, Len, temp; Rex=NewRegExp (R); Temp= Verify (Rex);//match the resulting stringlen = temp.length;//length                if(!len | | len = = 0)             Continue; if(r = = "y+")) {             if(Len!=2 && len! = 4)                ThrowError ("Bad year format: 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)                ThrowError ("Bad quarter format: Q can only appear 1 times"); FMT=Fmt.replace (Rex, o[r]); } Else if(r = = "H +") {            if(Len!=1 && len!=2)                ThrowError ("Bad hour format: H can only appear 1/2 times"); varh = (O[r] > 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)                 ThrowError ("Malformed number of milliseconds: s can only occur 1 times"); FMT=Fmt.replace (Rex, o[r]); }Else{//(r== "m+" | | r== "d+" | | r== "H +" | | r== "m+" | | r== "s+")Common (R, Rex)}} returnFMT;}

A few demonstration results for your reference:

Console.log (DateFormat (new Date (), ' yyyy year Q quarter m-month DD Day hh (M min s S S millisecond '));

Console.log (DateFormat (new Date (), ' yyyy yy ' Q quarter m month DD Day hh (m min s S msec)));

Console.log (DateFormat (new Date (), ' yyyy year Q quarter m-month DD Day hh (M min s S S millisecond '));

Console.log (DateFormat ("I am not a time object", ' yyyy year Q quarter m-month DD Day hh (M min s S S millisecond '));

Console.log (DateFormat (new Date (), ' yyyy year Q quarter MMM month DD Day hh (m min s S millisecond '));

Other effects are not listed, interested in the code can be copied down to direct testing on the line, there is any bug or need to be optimized, please be generous .

< Span style= "color: #808000;" > PS: Welcome reprint, Reprint please indicate the source: http://www.cnblogs.com/liuyitian/p/4136716.html

                          Writing is not easy, inevitably there are omissions and mistakes, please also be generous, please recommend

Learn a little bit more everyday code less knock a little bit 

JS time format

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.