Created
August 20, 2021 07:25
-
-
Save flxxyz/de413dca338db854df74734943001ba8 to your computer and use it in GitHub Desktop.
JS Date format (yyyy-MM-dd hh:mm:ss)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* - | |
* @param {string} fmt - | |
* @returns {string} - | |
*/ | |
Date.prototype.format = function (fmt) { | |
const dateObject = { | |
"y+": this.getFullYear(), | |
"M+": this.getMonth() + 1, // 月份 | |
"d+": this.getDate(), // 日 | |
"h+": this.getHours(), // 小时 | |
"m+": this.getMinutes(), // 分 | |
"s+": this.getSeconds(), // 秒 | |
"q+": Math.floor((this.getMonth() + 3) / 3), // 季度 | |
"S": this.getMilliseconds() // 毫秒 | |
}; | |
return Object.keys(dateObject) | |
.filter((key) => new RegExp(`(${key})`).test(fmt)) | |
.reduce((previousValue, key) => { | |
let replaceValue = dateObject[key]; | |
if (key === "y+" && new RegExp(`(${key})`).test(fmt)) { | |
return previousValue.replace(RegExp.$1, `${replaceValue}`.substr(4 - RegExp.$1.length)); | |
} | |
if (RegExp.$1.length !== 1) { | |
replaceValue = `00${replaceValue}`.substr(`${replaceValue}`.length); | |
} | |
return previousValue.replace(new RegExp(key), replaceValue); | |
}, fmt); | |
}; | |
// new Date().format('yyyy-MM-dd hh:mm:ss') | |
// return: 2021-08-20 14:28:49 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment