javascriptのDateで勘違いしたこと

プログラミング
アイキャッチ
スポンサーリンク

はじめに

Date型から、月と日を取得しようとしていた。

スポンサーリンク

間違っているところ

現在の日付.2019年12月5日なのに、
月が11,日が4になってしまっている。

  //現時点のDateを取得
const today = new Date();
console.log(today);//→Thu Dec 05 2019 14:31:31 GMT+0900 (日本標準時)
//月を取得
console.log(today.getMonth());//→11
//何日か取得
console.log(today.getDay());//→4
スポンサーリンク

修正後

  //月を取得
console.log(today.getMonth() + 1);//→12
//何日か取得
console.log(today.getDate());//→5
スポンサーリンク

おわり

getMonthって返却値が0~11なのですね。
[参考リンク]
(https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth)

getDateに関しては、1~31のようです。
参考リンク

getDay使ってたのは、完全に勘違いでした。
getDayは曜日を返却してくれるようです。(0~6)
参考リンク

コメント

タイトルとURLをコピーしました