Modern answer. Valid in Java since 2014, I think it came to Android a few years later.
java.time and ThreeTenABP
I Java because this is what I can write.
ArrayList<Integer> dateList = new ArrayList<>(Arrays.asList(1, 5, 2020));
LocalDate date = LocalDate
.of(dateList.get(2), dateList.get(1), dateList.get(0));
System.out.println("Date: " + date);
Output is:
Date: 2020-05-01
LocalDate
(opposite Calendar
) numbers months sanely, so 5 is May. If you intended June, don’t use the literal 5, it would be very confusing. If you cannot use 6 for June, use the built-in constant Calendar.JUNE
. And remember to add 1 when passing to LocalDate.of()
.
Since you need the date as a Calendar
object for your date picker, we need to convert. A Calendar
object includes time of day and time zone and more, so is really overkill, but we need to obey the date picker API, of course. It’s conventional to use the start of the day in the JVM’s time zone.
ZonedDateTime startOfDay = date.atStartOfDay(ZoneId.systemDefault());
Calendar oldfashionedCalendar = DateTimeUtils.toGregorianCalendar(startOfDay);
System.out.println(oldfashionedCalendar.getTime());
Fri May 01 00:00:00 CEST 2020
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both 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. Only in this case don’t use
DateTimeUtils
for the conversion, use the slightly simpler GregorianCalendar.from(startOfDay)
.
- In non-Android 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