The original source: www.hangge.com the original link: http://www.hangge.com/blog/cache/detail_1346.html
background
Sometimes we need to format the date in javascript, converting it to a fixed-format string. There are many JS date libraries available online, and we can implement them ourselves without using these libraries.
Extend Date
In order to facilitate us to format the output of Date, we first extend Date and add the format method. Calling the format method of the Date object later converts the Date to a String of the format we specify.
Date.prototype.format = function (fmt) {
var o = {
"M+": this.getMonth() + 1./ / in
"d+": this.getDate(), / /,
"h+": this.getHours(), / / hour
"m+": this.getMinutes(), / / points
"s+": this.getSeconds(), / / SEC.
"q+": Math.floor((this.getMonth() + 3) / 3), / / quarter
"S": this.getMilliseconds() / / ms
};
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;
}
Copy the code
case
1. Format the current time:
(new Date()).format("yyyy-MM-dd hh:mm:ss.S") / / the 17:01:25 2019-03-21. 928
(new Date()).format("yyyy-M-d h:m:s.S") / / the 17:2:37 2019-3-21. 719
Copy the code
2, format output specified time:
var date = new Date("The 2019-03-31 15:40:16. 0");
date.format("MM-dd hh:mm"); / / 03-31 double-break ` `
Copy the code
Javascript date format: learning from the original: www.hangge.com the original link: http://www.hangge.com/blog/cache/detail_1346.html
Welcome to qq group communication: 704028989