2016年5月24日火曜日

javascript Dateで前月と翌月の設定について

javascriptで日時を扱う時は、次のようにDateオブジェクトを生成して使用する。

  1. var date = new Date();

そして、Dateオブジェクトには月を設定する関数(setMonth)がある。
次のように使用する。

  1. date.setMonth(month);

なので、Dateオブジェクトの前月、翌月はsetMonthを設定することで可能だ。
前月の場合はこんな感じ。

  1. date.setMonth(date.getMonth() - 1);


翌月の場合はこんな感じ。

  1. date.setMonth(date.getMonth() + 1);


で、前月と翌月の設定はできそうであるが、はまったことがある。
当日が31日で、当日の前月と当日の翌月が30日までしかない場合に
当日(31日)の前月と当日が、setMonthだとうまく設定できなかったのだ。
次のコードのような場合だ。

  1. function dateTest1() {
  2.     var date = new Date();
  3.     date.setMonth(5);//6月
  4.     date.setDate(0);//5月の最終日を設定
  5.  
  6.     console.log("date.getMonth() = " + date.getMonth());
  7.     console.log("date.getDate() = " + date.getDate());
  8.  
  9.     var previousM = new Date(date.getTime());
  10.     previousM.setMonth(previousM.getMonth() - 1);
  11.  
  12.     console.log("previousM.getMonth() = " + previousM.getMonth());
  13.     console.log("previousM.getDate() = " + previousM.getDate());
  14.  
  15.     var nextM = new Date(date.getTime());
  16.     nextM.setMonth(nextM.getMonth() + 1);
  17.  
  18.     console.log("nextM.getMonth() = " + nextM.getMonth());
  19.     console.log("nextM.getDate() = " + nextM.getDate());
  20. }


このコードの実行結果は次のようになった。

  1. date.getMonth() = 4
  2. date.getDate() = 31
  3. previousM.getMonth() = 4
  4. previousM.getDate() = 1
  5. nextM.getMonth() = 6
  6. nextM.getDate() = 1


前月に設定したはずが当月と同じ。それで翌月に設定していたはずが翌々月になっている。
今回の場合、当日は5月31日である。それで当日のDateオブジェクトにたいしてsetMonthに当月の-1した値を設定すれば4月になるのではと思うのだが、4月31日なんてものはない。4月は30日までだ。なので、javascriptが5月1日にしている。(previousMのgetMonth()とgetDate()の結果)
なお、前月はsetMonthに当月の+1した値を設定すれば6月になるのではと思うのだが、6月31日なんてものはない。6月は30日までだ。なので、javascriptが7月1日にしている。(nextMのgetMonth()とgetDate()の結果)
それで、この問題をどう解消しようかと考えて次のコードで対応することにした。
どうしたかというと、setMonthを使用せずに、setDateを使用して、前月と翌月を設定させることにした。
setDate(0)は前月の最終日がされるので、当月のDateオブジェクトに対して、setDate(0)を行い前月を設定する。
そして、当月の最終日が設定されているDateオブジェクトに対して、setDate(date.getDate() + 1)をすることで、翌月を設定するようにしている。

  1. function dateTest2() {
  2.     var date = new Date();
  3.     date.setMonth(5);//6月
  4.     date.setDate(0);//5月の最終日を設定
  5.  
  6.     console.log("date.getMonth() = " + date.getMonth());
  7.     console.log("date.getDate() = " + date.getDate());
  8.  
  9.     var previousM = new Date(date.getTime());
  10.     previousM.setDate(0);
  11.  
  12.     console.log("previousM.getMonth() = " + previousM.getMonth());
  13.     console.log("previousM.getDate() = " + previousM.getDate());
  14.  
  15.     var nextM = new Date(date.getTime());
  16.     nextM.setDate(date.getDate() + 1);
  17.  
  18.     console.log("nextM.getMonth() = " + nextM.getMonth());
  19.     console.log("nextM.getDate() = " + nextM.getDate());
  20. }


コードの実行結果は次のようになった。
ちゃんと、前月と翌月が設定できていた。

  1. date.getMonth() = 4
  2. date.getDate() = 31
  3. previousM.getMonth() = 3
  4. previousM.getDate() = 30
  5. nextM.getMonth() = 5
  6. nextM.getDate() = 1

0 件のコメント :

コメントを投稿