2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React + FullCalendarで現在の月が不規則にずれる奇妙な問題に遭遇した

Posted at

どのような問題が起きたのか?

image.png

FullCalendarから表示している月を取得し、現在月として扱っていたが、
上記画像の通り不規則にずれる問題に遭遇した。

1~8月までは正常、9月がなぜか10月になり、10月からは正常に戻る。
コードは以下の通り

FullCalendar.js
datesSet={(dateInfo) => { // カレンダー表示切替時に呼び出し
  const fullCalendarDate = new Date(dateInfo.start); // 月の最初の日付を取得
  fullCalendarDate.setDate(fullCalendarDate.getDate()); // fullcalendarのオブジェクトに変換
  setCurrentYear(fullCalendarDate.getFullYear()); // 今年をStateにセット
  setCurrentMonth(fullCalendarDate.getMonth()); // 今月をStateにセット
}}

不規則に発生していたので問題の発見が遅れた、
一体何が原因だったのか?

原因:表示されている月の初日が取得されていたから

93f3e7d9f2d41fc3c8aa9fdf3f327d8a.png

FullCalendarの日付データ設定時にStateへ値をセットする場合、
dateInfoから取得すると "表示されている" 日付がstartとなるため発生していた。

dateinfoの中身は以下のようになっている
image.png
表示月は8月だが、startの日付は8月1日でなく7月28日となっている、

対策:日付+15 で表示月に対応させる

FullCalendar.js
datesSet={(dateInfo) => {
  const fullCalendarDate = new Date(dateInfo.start);
  fullCalendarDate.setDate(fullCalendarDate.getDate() + 15);
  setCurrentYear(fullCalendarDate.getFullYear());
  setCurrentMonth(fullCalendarDate.getMonth());
}}

FullCalendarの1行目は、最大でも先月の日付が7までしか入らないので、
仮に月が最も短い2月だったとしても7+15=22となり、翌月になることはない。
逆に表示日が1日の場合も16日となるため、先月となることもない。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?