A date Formatting Function implemented by JavaScript _ javascript tips-js tutorial

Source: Internet
Author: User
This article mainly introduces a date Formatting Function implemented by JavaScript. This article provides implementation code and examples. For more information, see, it is often necessary to format the date. Unlike the backend, there is a convenient method to call. You can define a format method in the date object prototype, as shown below:

The Code is as follows:


// Added the formatting method for the date and time prototype.
Date. prototype. Format = function (formatStr ){
Var str = formatStr;
Var Week = ['day', 'yi', '2', '3', '4', '5', '6'];

Str = str. replace (/yyyy | YYYY/, this. getFullYear ());
Str = str. replace (/yy | YY/, (this. getYear () % 100)> 9? (This. getYear () % 100). toString (): '0' + (this. getYear () % 100 ));
Var month = this. getMonth () + 1;
Str = str. replace (/MM/, month> 9? Month. toString (): '0' + month );
Str = str. replace (/M/g, month );

Str = str. replace (/w | W/g, Week [this. getDay ()]);

Str = str. replace (/dd | DD/, this. getDate ()> 9? This. getDate (). toString (): '0' + this. getDate ());
Str = str. replace (/d | D/g, this. getDate ());

Str = str. replace (/hh | HH/, this. getHours ()> 9? This. getHours (). toString (): '0' + this. getHours ());
Str = str. replace (/h | H/g, this. getHours ());
Str = str. replace (/mm/, this. getMinutes ()> 9? This. getMinutes (). toString (): '0' + this. getMinutes ());
Str = str. replace (/m/g, this. getMinutes ());

Str = str. replace (/ss | SS/, this. getSeconds ()> 9? This. getSeconds (). toString (): '0' + this. getSeconds ());
Str = str. replace (/s | S/g, this. getSeconds ());
Return str;
}

It is relatively simple to call, for example:

The Code is as follows:


Var d = new Date ();
Var str = d. Format ("yyyy-MM-dd hh: mm: ss ");
Console. log (str );

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.