日付フォーマットは言語やライブラリによって微妙に書き方が違ったりして覚えるのが面倒です。
JavaScriptならライブラリ不要で以下の定義を入れておけば足りそうな気がしたのでメモしておきます。
Date.prototype.format = function(formatter, utc) {
var month_en = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var wday_en = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var wday_ja = '日月火水木金土';
return formatter(utc ? {
year: this.getUTCFullYear(),
month: ('0' + (this.getUTCMonth() + 1)).slice(-2),
month_en: month_en[this.getUTCMonth()],
day: ('0' + this.getUTCDate()).slice(-2),
wday: this.getUTCDay(),
wday_ja: wday_ja.charAt(this.getUTCDay()),
wday_en: wday_en[this.getUTCDay()],
hour: ('0' + this.getUTCHours()).slice(-2),
minute: ('0' + this.getUTCMinutes()).slice(-2),
second: ('0' + this.getUTCSeconds()).slice(-2),
ms: ('00' + this.getUTCMilliseconds()).slice(-3)
} : {
year: this.getFullYear(),
month: ('0' + (this.getMonth() + 1)).slice(-2),
month_en: month_en[this.getMonth()],
day: ('0' + this.getDate()).slice(-2),
wday: this.getDay(),
wday_ja: wday_ja.charAt(this.getDay()),
wday_en: wday_en[this.getDay()],
hour: ('0' + this.getHours()).slice(-2),
minute: ('0' + this.getMinutes()).slice(-2),
second: ('0' + this.getSeconds()).slice(-2),
ms: ('00' + this.getMilliseconds()).slice(-3)
});
};
※IE8とかでも動くような書き方にしています。
//年月日曜日なら
new Date().format(({year, month, day, wday_ja}) => `${year}年${month}月${day}日(${wday_ja})`)
//=> 2020年06月19日(金)
//前0を消したいならNumber()で
new Date().format(({year, month, day, wday_ja}) => `${year}年${Number(month)}月${Number(day)}日(${wday_ja})`)
//=> 2020年6月19日(金)
//年月なら
new Date().format(({year, month}) => `${year}/${month}`)
//=> 2020/06
//時間なら
new Date().format(({hour, minute, second, ms}) => `${hour}:${minute}:${second}.${ms}`)
//=> 17:51:33.491
//分割代入やアロー関数、テンプレートリテラルが使えない場合は
new Date().format(function(t) { return t.hour + ':' + t.minute + ':' + t.second + ':' + t.ms })
//=> 17:51:33.491
//HTTPヘッダ用日付形式なら
new Date().format(t => `${t.wday_en.slice(0, 3)}, ${t.day} ${t.month_en.slice(0, 3)} ${t.year} ${t.hour}:${t.minute}:${t.second} GMT`, true)
//=> Fri, 19 Jun 2020 09:20:58 GMT
という感じで、どんな形式でもわりと直感的にかけるのではと思いました。