LoginSignup
1
1

More than 3 years have passed since last update.

Intl.DateTimeFormatを使った日付や時間の0詰め

Posted at

本題

最近仕事でNode.jsとV8のチェンジログを追っていたところ、Intl.DateTimeFormatという新機能を見つけました。使うと、日付や時間の0詰めを外部ライブラリに頼らずにシュッと書けそうなので試してみました。

サンプルコードは以下のような感じです。

const date = new Date('2020-01-01');
const dateStr =new Intl.DateTimeFormat('jp', {
  year: 'numeric', month: '2-digit', day: '2-digit',
}).format(date);
console.log(dateStr); // 2020/01/01
const date2 = new Date('2020-01-01');
const dateStr2 = new Intl.DateTimeFormat('jp', options = {
  year: 'numeric', month: '2-digit', day: '2-digit', 
  hour: '2-digit', minute: '2-digit', second: '2-digit', 
}).format(date2);
console.log(dateStr2); // 2020/01/01 09:00:00

コンストラクタIntl.DateTimeFormatの第2引数にはオブジェクトで表示のオプションが渡せます。プロパティ値が2-digitなら0詰めした値numericならそのままの値でフォーマットします。第1引数にはロケールを渡すのですが、各国の主要な表示方法でフォーマットするようです。

これで以下のようなコードとはおさばらじゃ!!

const date3 = new Date('2020-01-01');
const month = ('0' + (date3.getMonth()+1)).slice(-2);

参考

1
1
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
1
1