Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8902

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

$
0
0

本題

最近仕事で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);

参考


Viewing all articles
Browse latest Browse all 8902

Trending Articles