概要
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文字になるようにします。