0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Node.jsでYYYYMMDDの文字列を出力する

Last updated at Posted at 2020-02-03

#概要
Node.jsを使って現在日時からYYYYMMDDの文字列を出力します。
2020/2/3なら20200203となります。
少し工夫しないと202023とかになってしまいます。
#実際のコード

const createYYYYMMDD = () => {
    const today = new Date();
    const monthMM = ('0' + (today.getMonth() + 1)).slice(-2);
    const dayDD = ('0' + today.getDate()).slice(-2);
    return today.getFullYear().string() + monthMM + dayDD;
};

console.log(createYYYYMMDD);  // 20200203

##ポイント
getMonth()で得られる値は、現在の月(日)から1引いた値となります。
そのため1を足して(today.getMonth() + 1)います。
さらに'0' +として、先頭に0を付けた文字列に変換して、.slice(-2)で必ず2文字になるようにします。

0
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?