5
1

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 5 years have passed since last update.

JavaScriptのDate型を「2019-11-06」みたいな形式に変換

Posted at

JavaScriptのDate型のオブジェクトから、
「2019-11-06」みたいな形で、
・ハイフン区切り
・1桁の月や日は頭に0をパディング
にするのが面倒だったので、以下のような変換用関数を作りました。

//ハイフン区切りの文字列へ変換  ex)2019-11-06
function getDateString (date) {
  return date.getFullYear() + '-' 
    + ('0' + (date.getMonth() + 1)).slice(-2) + '-'
    + ('0' + date.getDate()).slice(-2)
}

DateオブジェクトのgetMonth()メソッドが0〜11を返すのが罠。

自分で今後も他でも使いそうなのと、
他の方にも役立つかもしれないので、置いておきます。

5
1
6

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?