Example of how to format and output a date using JS

Source: Internet
Author: User

Sometimes we need to format the date in javascript and convert it to a string in a fixed format. There are many ready-made JS date libraries available for use on the Internet. In fact, we can implement them ourselves without using these libraries.


1. Extend Date

To facilitate the formatting and output of the Date, expand the Date and add the format method. Call the format method of the Date object to convert the Date to a String in the specified format ).

Date. prototype. format = function (fmt ){
Var o = {
"M +": this. getMonth () + 1, // month
"D +": this. getDate (), // day
"H +": this. getHours (), // Hour
"M +": this. getMinutes (), // minute
"S +": this. getSeconds (), // second
"Q +": Math. floor (this. getMonth () + 3)/3), // quarter
"S": this. getMilliseconds () // millisecond
};
If (/(y +)/. test (fmt )){
Fmt = fmt. replace (RegExp. $1, (this. getFullYear () + ""). substr (4-RegExp. $1. length ));
  }
For (var k in o ){
If (new RegExp ("(" + k + ")"). test (fmt )){
Fmt = fmt. replace (RegExp. $1, (RegExp. $1. length = 1 )?
(O [k]): ("00" + o [k]). substr ("" + o [k]). length )));
    }
  }
Return fmt;
}

2. Example

(1) format the current output time

(New Date (). format ("yyyy-MM-dd hh: mm: ss. S") // 08:09:04. 423
(New Date (). format ("yyyy-M-d h: m: s. S") //. 18

(2) format the output at the specified time

Var date = new Date ("2016-08-24 15:40:16. 0 ");
Date. format ("MM-dd hh: mm"); // 08-24

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.