I am providing the modern answer.
java.time and ThreeTenABP
Use LocalDate
from java.time, the modern Java date and time API.
To take the current date
LocalDate currentDate = LocalDate.now(ZoneId.systemDefault());
System.out.println(currentDate);
When I ran this code just now, the output was:
2020-01-05
To get selected date in your date picker
int year = 2019;
int month = Calendar.DECEMBER; // but don’t use `Calendar`
int dayOfMonth = 30;
LocalDate selectedDate = LocalDate.of(year, month + 1, dayOfMonth);
System.out.println(selectedDate);
2019-12-30
Your date picker is using the same insane month numbering that the poorly designed and long outdated Calendar
class is using. Only for this reason, in an attempt to produce readable code, I am using a constant from that class to initialize month
. In your date picker you are getting the number given to you, so you have no reason to use Calendar
. So don’t.
And for the same reason, just as in your own code I am adding 1 to month
to get the correct month number (e.g., 12 for December).
Is the date in the past?
if (selectedDate.isBefore(currentDate)) {
System.out.println("" + selectedDate + " is in the past; not going to next activity");
} else {
System.out.println("" + selectedDate + " is OK; going to next activity");
}
2019-12-30 is in the past; not going to next activity
Converting to String and back
If you need to convert your selected date to a string in order to pass it through the Intent
(I don’t know whether this is a requirement), use the toString
and parse
methods of LocalDate
:
String dateAsString = selectedDate.toString();
LocalDate recreatedLocalDate = LocalDate.parse(dateAsString);
System.out.println(recreatedLocalDate);
2019-12-30
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.
- 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