Skip to content

Instantly share code, notes, and snippets.

@blackmiaool
Created February 3, 2019 14:26
Show Gist options
  • Save blackmiaool/66366915fc8758c64ae581ed1bfa1cc8 to your computer and use it in GitHub Desktop.
Save blackmiaool/66366915fc8758c64ae581ed1bfa1cc8 to your computer and use it in GitHub Desktop.
format date
Date.prototype.format = function(format) {
const zeros = ["", "0", "00", "000"];
const c = {
"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()
};
if (/(y+)/.test(format)) {
format = format.replace(
RegExp.$1,
`${this.getFullYear()}`.substr(4 - RegExp.$1.length)
);
}
for (const k in c) {
if (new RegExp(`(${k})`).test(format)) {
format = format.replace(
RegExp.$1,
RegExp.$1.length === 1
? c[k]
: (zeros[RegExp.$1.length] + c[k]).substr(`${c[k]}`.length)
);
}
}
return format;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment