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

js time and date formatting encapsulation function_javascript skills

May 16, 2016 pm 04:29 PM
js date time format

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.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to search previous Weibo by date on Weibo_How to search previous Weibo by date on Weibo How to search previous Weibo by date on Weibo_How to search previous Weibo by date on Weibo Mar 30, 2024 pm 07:26 PM

1. First open the mobile web browser, search for the Weibo web version, and click the avatar button in the upper left corner after entering. 2. Then click Settings in the upper right corner. 3. Click the version switching option in settings. 4. Then select the color version option in the version switch. 5. Click Search to enter the search page. 6. After entering the keywords, click Find People. 7. When the search completion interface appears, click Filter. 8. Finally, enter the specific date in the release time column and click Filter.

How much does a Douyin level 10 light sign cost? How many days does it take to create a level 10 fan sign? How much does a Douyin level 10 light sign cost? How many days does it take to create a level 10 fan sign? Mar 11, 2024 pm 05:37 PM

On the Douyin platform, many users are eager to obtain level certification, and the level 10 light sign shows the user's influence and recognition on Douyin. This article will delve into the price of Douyin’s level 10 light boards and the time it takes to reach this level to help users better understand the process. 1. How much does a level 10 Douyin light sign cost? The price of Douyin's 10-level light signs will vary depending on market fluctuations and supply and demand. The general price ranges from a few thousand yuan to ten thousand yuan. This price mainly includes the cost of the light sign itself and possible service fees. Users can purchase level 10 light signs through Douyin’s official channels or third-party service agencies, but they should pay attention to legal channels when purchasing to avoid false or fraudulent transactions. 2. How many days does it take to create a level 10 fan sign? Reach level 10 light sign

How to remove the date that appears automatically when printing from PPT handouts How to remove the date that appears automatically when printing from PPT handouts Mar 26, 2024 pm 08:16 PM

1. Let me first talk about the method I used at the beginning, maybe everyone is using it too. First, open [View]——]Remarks Template[. 2. A place where you can actually see the date after opening it. 3. Select it first and delete it. 4. After deleting, click [Close Master View]. 5. Open the print preview again and find that the date is still there. 6. In fact, this date was not deleted here. It should be in the [Handout Master]. Look at the picture below. 7. Delete the date after you find it. 8. Now when you open the preview and take a look, the date is no longer there. Note: In fact, this method is also very easy to remember, because the printed handouts are handouts, so you should look for the [Handout Master].

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How long does it take to clear the Elden Ring? How long does it take to clear the Elden Ring? Mar 11, 2024 pm 12:50 PM

Players can experience the main plot of the game and collect game achievements when playing in Elden's Circle. Many players don't know how long it takes to clear Elden's Circle. The player's clearance process is 30 hours. How long does it take to clear the Elden Ring? Answer: 30 hours. 1. Although this 30-hour clearance time does not refer to a master-like speed pass, it also omits a lot of processes. 2. If you want to get a better game experience or experience the complete plot, then you will definitely need to spend more time on the duration. 3. If players collect them all, it will take about 100-120 hours. 4. If you only take the main line to brush BOSS, it will take about 50-60 hours. 5. If you want to experience it all: 150 hours of base time.

How to set the time for publishing works on Xiaohongshu? Is the time for publishing the work accurate? How to set the time for publishing works on Xiaohongshu? Is the time for publishing the work accurate? Mar 24, 2024 pm 01:31 PM

Xiaohongshu, a platform full of life and knowledge sharing, allows more and more creators to express their opinions freely. In order to get more attention and likes on Xiaohongshu, in addition to the quality of content, the time of publishing works is also crucial. So, how to set the time for Xiaohongshu to publish works? 1. How to set the time for publishing works on Xiaohongshu? 1. Understand the active time of users. First, it is necessary to clarify the active time of Xiaohongshu users. Generally speaking, 8 pm to 10 pm and weekend afternoons are the times when user activity is high. However, this time period will also vary depending on factors such as audience group and geography. Therefore, in order to better grasp the active period of users, it is recommended to conduct a more detailed analysis of the behavioral habits of different groups. By understanding users’ lives

Detailed explanation of Linux file time viewing techniques Detailed explanation of Linux file time viewing techniques Feb 21, 2024 pm 01:15 PM

Detailed explanation of Linux file time viewing techniques In Linux systems, file time information is very important for file management and tracking changes. The Linux system records file change information through three main time attributes, namely access time (atime), modification time (mtime) and change time (ctime). This article details how to view and manage this file time information, and provides specific code examples. 1. Check the file time information by using the ls command with the parameter -l to list the files.

Revealed secrets of cell phone format recovery methods (mobile phone malfunction? Don't worry) Revealed secrets of cell phone format recovery methods (mobile phone malfunction? Don't worry) May 04, 2024 pm 06:01 PM

Nowadays, we will inevitably encounter some problems such as being unable to turn on the phone or lagging, such as system crash, but during use, mobile phones have become an indispensable part of our lives. We are often at a loss, and sometimes, there are no solutions to these problems. To help you solve cell phone problems, this article will introduce you to some methods of cell phone format recovery and restore your phone to normal operation. Back up data - protect important information, such as photos and contacts, from being lost during the formatting process. Before formatting your phone, the first thing to consider is to back up important data and files on your phone. To ensure data security, or choose to transfer files to a cloud storage service, you can back it up by connecting to a computer. Use the system's built-in recovery function - simple

See all articles