0

How can I set the maximum date of a calendar using setMaxDate if I have the date with the format dd/mm/yyy?

I'm developing for Android.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
alexC
  • 133
  • 1
  • 12

1 Answers1

1

I am assuming that you mean android.widget.DatePicker.setMaxDate.

java.time and ThreeTenABP

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/u");
    String maxDateString = "21/12/2019";
    long maxDateInMillis = LocalDate.parse(maxDateString, dateFormatter)
            .atStartOfDay(ZoneId.systemDefault())
            .toInstant()
            .toEpochMilli();
    yourDatePicker.setMaxDate(maxDateInMillis);

In my time zone the example date used above, 21/12/2019, produces a maxDateInMillis of 1 576 882 800 000. According to Epoch Converter (link at the bottom) this means

Your time zone: lørdag d. 21. december 2019 kl. 00:00:00 GMT+01:00

According to the linked documentation DatePicker uses the device time zone.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161