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

JavaScriptでYYYYMMDDのミニマム

Posted at

おそらくこれが最小

sample.js
new Date().toISOString().split('T')[0].replaceAll('-','')

実行結果

image.png

解説

  • JSで使える日付フォーマットでちょうど良さそうなのが、ISO 8601形式
  • ISO 8601 形式はYYYY-MM-DDTHH:mm:ss.sssZ
    • 例)'2026-01-05T11:16:15.287Z'
  • Tの左が日付
  • Tの右が時刻(ミリ秒込)
  • ミリ秒以降を取り除きたかったら、ピリオドの左側だけをとればいい

別解

image.png

理屈の上では正しいんだけど、getMonthが0始まりとか、何も考えないと0埋めを忘れたりする人もいたりで、レビューに脳を使うことになる。あと2月2日とか3月3日とかには、月と日が入れ替わっていても分かりづらいのもあって日付を連結させるロジックは原則手作りしたくないしさせたくない。

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