5
4

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 5 years have passed since last update.

[Android] datePickerでsetMaxDateやsetMinDateで日付範囲を指定するときに気をつけること

Last updated at Posted at 2015-09-10
Fatal Exception: java.lang.IllegalArgumentException
Time not between Wed Sep 09 19:07:07 JST 2015 and Wed Jun 01 19:07:07 JST 2016

こんなクラッシュレポートが発生していました。
datePicker.setMaxDateとdatePicker.setMinDateでの範囲に誤りがある。

調べてみると、Calendarクラスで日付だけセットしても時分秒ミリ秒でズレが残ってました。
なので、日付の指定の他にMinDateには0時0分0秒00、MaxDateには23時59分59秒99というような範囲を設定する必要があります。


//MaxDateの設定
Calendar maxCal = Calendar.getInstance();
maxCal.add(Calendar.MONTH, 6); //6ヶ月後

maxCal.set(Calendar.HOUR_OF_DAY, maxCal.getMaximum(Calendar.HOUR_OF_DAY));
maxCal.set(Calendar.MINUTE, maxCal.getMaximum(Calendar.MINUTE));
maxCal.set(Calendar.SECOND, maxCal.getMaximum(Calendar.SECOND));
maxCal.set(Calendar.MILLISECOND, maxCal.getMaximum(Calendar.MILLISECOND));

datePicker().setMaxDate(maxCal.getTimeInMillis());

//MinDateの設定
Calendar minCal = Calendar.getInstance(); // 本日

minCal.set(Calendar.HOUR_OF_DAY, minCal.getMinimum(Calendar.HOUR_OF_DAY));
minCal.set(Calendar.MINUTE, minCal.getMinimum(Calendar.MINUTE));
minCal.set(Calendar.SECOND, minCal.getMinimum(Calendar.SECOND));
minCal.set(Calendar.MILLISECOND, minCal.getMinimum(Calendar.MILLISECOND));
datePicker().setMinDate(minCal.getTimeInMillis());
5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?