Detailed JavaScript time format _javascript techniques

Source: Internet
Author: User
Tags dateformat getdate throw exception

Thanks to a predecessor to write the JS format date and time JS code, very good very powerful!!!

Objective:

JS provides various property methods for acquiring time date objects, such as: GetDate method | Getday Method | getFullYear Method | GetHours method ... And so on, but did not like Java as a way to provide users with the template (pattern) provided by the user to format the specified time object, so they encapsulate a small method, only for everyone to ridicule-.-, there are good suggestions also look generous to recommend Oh.

Use the Knowledge point:

arguments: This object represents the function being executed and the arguments of the function that called it. Cannot be explicitly created, although it has a length property and can be evaluated as an array in the "[]" syntax, but it is not an array.

typeof object: An operator that returns a string representing the data type of an expression. Six possible: "Number," "String," "Boolean," "Object," "function," and "undefined."

Object.constructor: Represents a function that creates an object. Object must be the name of an object or function. 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 that contains the result of the lookup. No match found, it returns NULL. Matching elements of the same type in an array do not recur.

Str.split (REX|STR): Splits a string into substrings with a regular object or substring, and then returns the result as an array of strings.

Throw error (' msg '): Throws an error with message information. Throw can be followed by any expression.

• There are also some for. In use, three-mesh operator, substr these are not spoken, relatively simple.

Code fragment:

/** * ***JS Time Date Format * * * * <br> * <p> * Template string in a rigorous format, exceeding will throw an exception, and each type of format can only occur once, such as: yyyy-mm-yyyy format will throw exception * </p> * Y-year LENGTH:2/4 bit <br> * Q quarter length:1 bit <br> * M-month length:1~2 bit <br> * D-day length:1~2 bit &LT;BR&G
 T * H-time length:1~2 bit 24-hour system, H:12-hour <br> * M-length:1~2 bit <br> * S-SEC length:1~2 bit <br> * S-millisecond length : Fixed 1-bit * @param {Date type Object} Date * @param {String type template string} FMT * @return formatted time date String * @author Lyt * blongs:http://www . cnblogs.com/liuyitian//function DateFormat (date, FMT) {if (arguments.length!= 2)///parameter number check throw Error (' Argume
  NTS length not valid '); if (!date | | (typeof date!= ' object ') | | (D.constructor!= Date))
  parameter legality check throw Error (Arguments[0] + ': Type is not date type '); if (/h+/.test (FMT) &&/h+/.test (FMT)) Throw error ("Hour format error, same type can only occur once!")
  "); /* template parameter check, regular verification method * * var verify = function (Rex) {var arr = new RegExp (Rex). EXEC (FMT);//Get matching result array if (!arr)//Horse
    Match failure returns return ""; if (FMT.Split (REX). length > 2//The same type interval occurs multiple times throw error ("FMT format error: Same type can only appear once!")
    ");
  return arr[0];
  };
    /** * Provides the month, day, hour, minute, second universal matching replacement * @param {object O property key} R * @param {R corresponds to regular object} Rex **/var common = function (r, Rex) {
    if (Len!=1 && len!=2) throw error ("Month format error: M can only occur 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 store 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 O'Clock "h+": Date.gethours () + "",//12 O'Clock "m+": date.getminutes () + "",//Sub "s+": date.getseconds () + "",//sec "s+": Date
    . Getmilliseconds ()//millisecond} for (Var r in O) {var rex, Len, temp;
    Rex = new RegExp (r); temp = Verify (Rex); Match the resulting 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 1 times");
    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] > 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 number format error: S can only appear 1 times");
    Fmt=fmt.replace (Rex, o[r]);
}else {//(r== "m+" | | r== "d+" | | r== "h+" | | r== "m+" | | r== "s+") Common (R, Rex)}} return FMT; }

Several demonstration effect, for everybody's Reference:

Console.log (DateFormat (new Date), ' yyyy q quarter m DD Day hh (m minute s S milliseconds '));


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


Console.log (DateFormat (new Date), ' yyyy q quarter m DD Day hh (m minute s S milliseconds '));


Console.log ("I am not a time object", ' yyyy q quarter m month DD Day hh ' m minute s ' s milliseconds '));


Console.log (DateFormat (new Date), ' yyyy q quarter mmm month dd Day hh ' m minute s S milliseconds ');

Other effects are not listed, interested in the code can be copied down directly to test the line, there are any bugs or need to optimize the place please be generous.

Through the above content to give you detailed JavaScript time format related knowledge, I hope you like.

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.