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

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

$
0
0

概要

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

実際のコード

constcreateYYYYMMDD=()=>{consttoday=newDate();constmonthMM=('0'+(today.getMonth()+1)).slice(-2);constdayDD=('0'+(today.getDay()+1)).slice(-2);returntoday.getFullYear().string()+monthMM+dayDD;};console.log(createYYYYMMDD);// 20200203

ポイント

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


Viewing all articles
Browse latest Browse all 8883

Trending Articles