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

More than 1 year has passed since last update.

カレンダーの日付を取得

Posted at

はじめに

学習の備忘録として残します。ご指摘等がございましたら教えていただけますと嬉しいです。
現在Googleカレンダーを作成しています。
使用したライブラリはdayjsです。

実装

前月の日付の計算

import dayjs, {Dayjs} from "dayjs";
import ja from "dayjs/locale/ja"
dayjs.locale(ja);

const Calendar = {
  // 今日の日付を取得
  const today = dayjs();

  // 前月の日付を取得
  const startDay: number = today.startOf("month").day();

  const lastDayOfLastMonth: number = today
    .subtract(1, "month")
    .endOf("month")
    .date();

  const daysFromPreviousMonth: Dayjs[] = Array(startDay)
    .fill(null)
    .map((_, index) => {
      return dayjs(
        new Date(
          today.year(),
          today.month() - 1,
          lastDayOfLastMonth - startDay + index + 1
        )
      );
    });
  return <div></div>
};

前月の日付の取得のところを詳しく説明していく

  const daysFromPreviousMonth: Dayjs[] = Array(startDay)
    .fill(null)
    .map((_, index) => {
      return dayjs(
        new Date(
          today.year(),
          today.month() - 1,
          lastDayOfLastMonth - startDay + index + 1
        )
      );
    });

ここでは新しくdayjsのオブジェクトを作っている。
例えば、前月が30日(火)だとした場合
水曜日は日曜日を0だとした場合は3であるから
・日曜日の日付:30 - 3 + 0 + 1 = 28
・月曜日の日付:30 - 3 + 1 + 1 = 29
・火曜日の日付:30 - 3 + 2 + 1 = 30

現在の日付の実装

  const nowMonth = dayjs().daysInMonth();
  const daysFromNowMonth: Dayjs[] = Array(nowMonth)
    .fill(null)
    .map((_) => {
      return dayjs(new Date(today.year(), today.month(), index + 1));
    });

現在の日付の日数を取得する。そして前月と同じようにデータをまとめる。

来月の日付の実装

  const nowMonthFinish: number = today.endOf("month").day();
  const nextMonthLengh: number = 6 - nowMonthFinish;
  const daysFromNextMonth: Dayjs[] = Array(nextMonthLengh)
    .fill(null)
    .map((_, index) => {
      return dayjs(new Date(today.year(), today.month() + 1, index + 1));
    });

現在の月の終わりが何曜日か取得する。
そしてmap関数で来月の曜日を入れていく。

最後に全ての日付を配列に入れる

  const calendarArray: Dayjs[] = [
    ...daysFromPreviousMonth,
    ...daysFromNowMonth,
    ...daysFromNextMonth,
  ];

おわりに

ロジックを考えることに慣れていないので練習として丁寧にやっていきました。
関数名も適当になってしまっているので今後改善していくようにします。

0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?