LoginSignup
0
0

More than 3 years have passed since last update.

Dateでよく使うテクニック

Posted at

はじめに

JavascriptのDateはなんか癖があって使いづらいなー
Moment.js使っとこ:innocent:
って感じでコードを書いていましたが、この際、Dateもしっかり理解しておこうと思ってメモとして残しておきます。

Dateを使う前に知っておきたいこと

Dateで月の扱い方をミスると別の月の情報を取得するので注意です。
例えば、12月のDateオブジェクトを生成するときは、new Date('2020', '11')のようにしてあげる必要があります。

取得したい月 - 1

曜日

getDay()を使うと曜日を取得できるのですが、月曜とかMonという値が取得できるわけではないので注意です。
getDay()は日曜から土曜までを0~6の値で返してくれます。
例えば、getDay()の値が1であれば月曜ということになります。
月とかMonというような文字列で取得したい場合は以下のようなコードを書きましょう!

main.js
const dayOfWeek = ['', '', '', '', '', '', ''];
const date = new Date(2020, 11); // 2020年12月1日のDateオブジェクトを生成
const i = date.getDay(); // 2020年12月1日は火曜なので2という値が返ってくる
console.log(dayOfWeek[i]); // コンソールに火と出力される

テクニック

月末の取得

Dateの第三引数に0を渡してgetDate()してあげると月末の日を取得できます。

main.js
new Date(2020, 10, 0).getDate(); // 31 2020年10月の最終日
new Date(2020, 11, 0).getDate(); // 30 2020年11月の最終日
new Date(2020, 12, 0).getDate(); // 31 2020年12月の最終日

第三引数に0を渡すことによって前の月の最終日という意味になります。

指定した月の日と曜日を配列にする

配列に日と曜日のオブジェクトを月の日数分格納するには、まず、指定する月が何日あるのかをプログラムで書きます。
今回は2020年12月を例に作成します。

main.js
let date = new Date(2020, 11);
let num = new Date(2020, 12, 0).getDate(); // 31

これで2020年12月が何日あるかわかりました。
次は日数分繰り返す処理を書きます。

main.js
let date = new Date(2020, 11);
let num = new Date(2020, 12, 0).getDate(); // 31
for (let i = 0; i < num; i++) {

}

日数分繰り返すプログラムが書けたのであとは曜日のオブジェクトを配列に格納していきます。
date.setDate(date.getDate() + 1)で翌日を表します。

main.js
const dayOfWeek = ["", "", "", "", "", "", ""];
const dates = [];
let date = new Date(2020, 11);
let num = new Date(2020, 12, 0).getDate(); // 31
for (let i = 0; i < num; i++) {
  dates.push({
    date: date.getDate(), // 日
    dayOfWeek: dayOfWeek[date.getDay()], // 曜日
  });
  date.setDate(date.getDate() + 1); // 翌日
}
console.log(dates);

おわりに

気が向いたらmoment.jsバージョンも書きます

0
0
2

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
0
0