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