java.time and ThreeTenABP
Use LocalDate from java.time, the modern Java date and time API. It’s much nicer to work with.
    int year = 2019;
    int month = 10;
    int day = 15;
    LocalDate date = LocalDate.of(year, month, day);
    System.out.println(date);
The output from this snippet is:
2019-10-15
LocalDate numbers both years and months the same way humans do, so there’s no subtracting funny values to adjust. If you need a Date for an API not yet upgraded to java.time, the conversion goes like this:
    Instant startOfDay = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
    Date oldfashionedDate = DateTimeUtils.toDate(startOfDay);
    System.out.println(oldfashionedDate);
Tue Oct 15 00:00:00 CEST 2019
The classes Date, Calendar and GregorianCalendar are all poorly designed and all long outdated. So do consider not using them.
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 for converting from InstanttoDateuseDate.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.bpwith subpackages.
Links