Home > Web Front-end > JS Tutorial > js time and date formatting encapsulation function_javascript skills

js time and date formatting encapsulation function_javascript skills

WBOY
Release: 2016-05-16 16:29:37
Original
1559 people have browsed it

Although js provides various different attribute methods for obtaining time Date objects, such as: getDate method | getDay method | getFullYear method | getHours method ... ... etc., but it does not provide a method like Java for users to format the specified time object according to the template (pattern) provided by themselves, so I encapsulated a small The method is just for everyone to laugh at -.-. If you have any good suggestions, please give them generously.

Knowledge points used:

Arguments: This object represents the parameters of the function being executed and the function that calls it. It cannot be created explicitly. Although it has a length attribute and can be retrieved using the "[]" syntax like an array, it is not an array. typeof object: operator, returns a string representing the data type of the expression. Six possibilities: "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 search in a string using a regular expression pattern and returns an array containing the results of the search. If no match is found, it returns null. Matching elements of the same type will not appear repeatedly in the array. str.split(Rex|str): Split a string into substrings using a regular object or substring, and then return the result as a string array. throw Error('msg'): Throw an Error with Message information. throw can be followed by any expression. There are also some usages of for..in, ternary operator, and substr, which I won’t go into, as they are relatively simple.

Code snippet:

Copy code The code is as follows:

/**
* ***js time and date formatting***

*


* The template string adopts a strict format. If it exceeds the limit, an exception will be thrown. Each type of format can only appear once, such as: yyyy-mm-yyyy format will throw an exception
*


* y-year length: 2/4 digits

* q-quarter length: 1 digit

* M-month length: 1~2 digits

* d-日 length: 1~2 digits

* H-hour length: 1~2 digits in 24-hour format, h: 12-hour format

* m-minute length: 1~2 digits

* s-second length: 1~2 digits

* S-millisecond length: fixed 1 digit
* @param {Date type object} date
* @param {String type template string} fmt
* @return formatted time and date string
* @author lyt
​*/
function DateFormat(date, fmt){
If (arguments.length != 2) // Parameter number verification
          throw Error('arguments length is illegal');
If (!date || (typeof date != 'object') || (d.constructor != Date)) // Parameter validity verification
          throw Error(arguments[0] ':The type is not a Date type');
If (/H /.test(fmt) && /h /.test(fmt))
throw Error("The hour format is wrong, the same type can only appear once in a row!");
/* Template parameter verification, regular verification method */
var verify = function(Rex){
          var arr = new RegExp(Rex).exec(fmt); // Get the matching result array
           if (!arr) // Returns
if the match fails              return "";
If (fmt.split(Rex).length > 2) // The same type appears multiple times
throw Error("fmt format error: the same type can only appear once in a row!");
          return arr[0];
};
/**
* Provide universal matching replacement for month, day, hour, minute and second
* @param {object o attribute key} r
* @param {r corresponds to the 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 hours
"h ": date.getHours() "", // 12 o'clock
"m ": date.getMinutes() "", // Minutes
"s ": date.getSeconds() "", // Seconds
"S ": date.getMilliseconds() // Milliseconds
}
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("Quarter 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("Milliseconds format error: S can only appear once");
                                            fmt=fmt.replace(rex, o[r]);
                                   // (r=="M " || r=="d " || r=="H " || r=="m " || r=="s ")
common(r, rex)
                                                                                                              }
Return fmt;
}

Here are some demonstration effects for your reference:

Copy code The code is as follows:
console.log(DateFormat(new Date(),'yyyyyear q quarter M month dd day HH hour m minute s second S millisecond'));

Copy code The code is as follows:
console.log(DateFormat(new Date(),'yyyyyearyy Q quarter M month dd day HH hour m minute s second S millisecond'));

Copy code The code is as follows:
console.log(DateFormat(new Date(),'yyyyyear q quarter M month dd day Hh hour m minute s second S millisecond'));

Copy code The code is as follows:
console.log(DateFormat("I am not a time object",'yyyy Year q quarter M month dd day Hh hour m minute s second S millisecond'));

Copy code The code is as follows:
console.log(DateFormat(new Date(),'yyyyyear q quarter MMM month dd day HH hour m minute s second S millisecond'));

I won’t list other effects one by one. If you are interested, you can just copy the code and test it directly. If there are any bugs or areas that need to be optimized, please feel free to correct them.

The above is an introduction to this very useful encapsulated function. Isn’t it very practical? Friends can use it directly in their own projects.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template