0
0

More than 3 years have passed since last update.

JavaScriptの日付フォーマットはこれだけあれば十分な気がする

Posted at

日付フォーマットは言語やライブラリによって微妙に書き方が違ったりして覚えるのが面倒です。

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

という感じで、どんな形式でもわりと直感的にかけるのではと思いました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0