JavaScript Custom date Format function __javascript

Source: Internet
Author: User
Tags getdate
One of our more common ways to extend JavaScript is to extend Date.prototype. Because we know that the Date class only provides a few methods to get date elements, such as getDate (), getMinute () ... but there is no formatting method for converting to a specific string. So, use these subtle methods to encapsulate and combine the date string form we want. In general, the formatting function can be defined on the prototype of the Date object, or it can be written in a separate method. The operations that define the prototype method are Date.prototype.format = function (date) {……}, and you can directly use new Date (). Format (YYYY: MM: DD) when you use it, as if it were the native method of the Date object. But the definition of the prototype method is slightly inadequate to "hack" the JS prototype. This must be considered when designing the API. My suggestion is that users make decisions based on their own judgments, but the calling methods are different and do not affect the logic of the process.

The following example is a JavaScript date formatting function written in a separate function, a separate format function. Returning to this knowledge point of formatting, we examine how it is implemented and what principles are used. Although traditional string concatenation such as indexOf () + substr () can be implemented, it is obviously not only inefficient, but also the code is verbose. It is still a suitable method to introduce regular expressions. First write the string regular and then perform the hit matching of the result. Let's look at the example from Steven Levithan first:



This piece of code considers date processing more thoroughly. Let's go into the principle and look at its mystery, how to handle dates!

In the date string template, we have agreed to use yyyy / mm / dd and other meaningful symbols to represent a certain element of the date, such as y is the year and year, m is the month and month, and d is the day and day. If it is uppercase, pay attention to distinguish it. The uppercase M stands for minutes, and the lowercase m stands for months. In short, this is a convention that we have standardized artificially, that is, the so-called "mask" of the above code. According to this convention, you can enter the parameters of the pattern you want to format, and you can output the value of the date type to a printable string. As for the parsed date process, first, according to all the requirements of Mask, get each element of the date one by one (getDate (), getMinute () ... can be obtained quickly), and then follow the actual conditions of Mask, which is Mask The .replace (regular, element) method replaces the string template and the element. The replacement process still uses the flag as a flag to match the matching table one by one. As for the regular part, the key is to understand the process of token and replace () functions. Attend the code comments above to learn the internal details.

Wouldn't it be tiring to enter lengthy Mask strings every time? We can reduce our workload by defining constants:



Steve's dateFormat is enough to complete most date conversion tasks, but in the vast code, we found a better solution. In less than 20 lines of code, the regular use can be freely applied, which is JS from Moon Shadow's predecessor!



The principle is similar to the Steve method, but the more condensed code combines skill and comprehensiveness. Starting from line 12 of the source code, the test () method not only can detect whether there is a minimum function of matching, but actually has a memory matching result, and generates a RegExp. $ 1 result group to process the year (at the beginning I think test () is efficient and Will not produce results, but it is not.) Then, use new RegExp to create a regular expression instance in the form of a string, which is another clever place-because it is directly connected to the hash table of o! Then go according to the law, first test whether the match matches, and if necessary, replace it.

In addition, ("00" + o [k]). Substr (String (o [k]). Length) in the code is also interesting. What does it mean to add two? The original purpose was to get the last two digits of the array. This is a technique for comprehensively using the substr () method. The first parameter of substr is the index to be truncated. If you do not specify the second parameter index, the string is retained to the end (str.length). So, how many digits do we add in advance, and if the original fixed string length does not change (String (o [k] .length)), then how many digits are left. (P.s "00" is equivalent to a placeholder, and other strings "XX" can be used instead of no difference)

Still feel that this code has a lot of difficulties? We try to rewrite Moon Shadow's function into more readable code. The principle tends to be consistent but there are not so many skills. I believe this can save everyone's time. It is not too late to look at Moon Shadow's code again.



2011--1-7:

Date formatting code from ext 4.0, how to say that the string is converted to js standard date? See how the new ext is made?



The date constructor can also determine the date by calculating the number of milliseconds since 1970? -Indeed, this works, too-that is to say, inferior, from this problem, the smallest unit of js date is milliseconds.

Final version:

/ **
 * Date formatting. See blog post for details: http://blog.csdn.net/zhangxin09/archive/2011/01/01/6111294.aspx
 * e.g: new Date (). format ("yyyy-MM-dd hh: mm: ss")
 * @param {String} format
 * @return {String}
* /
Date.prototype.format = function (format) {
    var $ 1, o = {
        "M +": this.getMonth () + 1, // month, counting from 0
        "d +": this.getDate (), // date
        "h +": this.getHours (), // hours
        "m +": this.getMinutes (), // minutes
        "s +": this.getSeconds (), // seconds
// quarter
        "q +": Math.floor ((this.getMonth () + 3) / 3),
        "S": this.getMilliseconds () // thousand seconds
    };
    var key, value;
 
    if (/(y+)/.test(format)) {
        $ 1 = RegExp. $ 1,
        format = format.replace ($ 1, String (this.getFullYear ()). substr (4-$ 1));
    }
 
    for (key in o) {// If this parameter is not specified, the substring will continue to the end of stringvar.
        if (new RegExp ("(" + key + ")"). test (format)) {
            $ 1 = RegExp. $ 1,
value = String (o [key]),
value = $ 1.length == 1? value: ("00" + value) .substr (value.length),
    format = format.replace ($ 1, value);
        }
    }
    return 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.