Date.prototype.format = function(format) {
const zeroPad = (len, str) => String(str).padStart(len, "0")
const p = zeroPad.bind(null, 2)
const replacement = {
yyyy: this.getFullYear(),
MM: p(this.getMonth() + 1),
dd: p(this.getDate()),
HH: p(this.getHours()),
mm: p(this.getMinutes()),
ss: p(this.getSeconds()),
fff: zeroPad(3, this.getMilliseconds()),
}
return format.replace(new RegExp(Object.keys(replacement).join("|"), "g"), e => replacement[e])
}
new Date().format("yyyy/MM/dd HH:mm:ss.fff")
// "2018/03/02 19:00:11.780"
高機能化 (C# や PHP を参考にしてる)
Date.prototype.format = function(format) {
const zeroPad = (len, str) => String(str).padStart(len, "0")
const p = zeroPad.bind(null, 2)
const sign = n => (~~n < 0 ? "-" : "+")
const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
const apm = ["AM", "PM"]
const v = {
y: this.getFullYear(),
M: this.getMonth() + 1,
d: this.getDate(),
H: this.getHours(),
m: this.getMinutes(),
s: this.getSeconds(),
f: this.getMilliseconds(),
w: this.getDay(),
u: this.getTime(),
o: -this.getTimezoneOffset(),
}
const replacement = {
yyyy: v.y,
yy: p(v.y % 100),
MMMM: months[v.M - 1],
MMM: months[v.M - 1].substr(0, 3),
MM: p(v.M),
M: v.M,
dddd: days[v.w],
ddd: days[v.w].substr(0, 3),
dd: p(v.d),
d: v.d,
HH: p(v.H),
H: v.H,
hh: p(v.H % 12),
h: v.H % 12,
mm: p(v.m),
m: v.m,
ss: p(v.s),
s: v.s,
fff: zeroPad(3, v.f),
f: v.f,
tt: apm[+(v.H >= 12)],
t: apm[+(v.H >= 12)][0],
UU: v.u,
U: parseInt(v.u / 1000),
zzz: sign(v.o) + p(~~(v.o / 60)) + ":" + p(v.o % 60),
zz: sign(v.o) + p(~~(v.o / 60)),
z: sign(v.o) + ~~(v.o / 60),
}
return format.replace(new RegExp(Object.keys(replacement).join("|"), "g"), e => replacement[e])
}
new Date().format("yyyy/MM/dd HH:mm:ss.fff")
// "2018/03/02 19:00:11.780"
"timezone offset: " + new Date().format("zzz")
// "timezone offset: +09:00"
"unixtimestamp: " + new Date().format("U")
// "unixtimestamp: 1519987796"
"unixtimestamp(ms): " + new Date().format("UU")
// "unixtimestamp(ms): 1519987802170"
new Date().format("tt t MMMM MMM dddd ddd")
// "PM P March Mar Friday Fri"