Skip to content

Instantly share code, notes, and snippets.

@flxxyz
Created August 20, 2021 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flxxyz/de413dca338db854df74734943001ba8 to your computer and use it in GitHub Desktop.
Save flxxyz/de413dca338db854df74734943001ba8 to your computer and use it in GitHub Desktop.
JS Date format (yyyy-MM-dd hh:mm:ss)
/**
* -
* @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