java.time
public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
LocalDate date = LocalDate.of(year, Month.values()[month], dayOfMonth);
String selectedDates = date.toString();
dateTest.setText(selectedDates);
}
As has been said in comments, you need to pick up the date that the user has chosen from the arguments passed to onSelectedDayChange
. Unfortunately the month
passed is 0-based, a number in the interval from 0 for January through 11 for December. Month.values()[month]
is my trick for obtaining the correct Month
object. If you prefer, you may instead just add 1:
LocalDate date = LocalDate.of(year, month + 1, dayOfMonth);
I am further exploiting the fact that LocalDate.toString
produces the format you want, so we need no explicit formatter. The format is ISO 8601.
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, I’m told) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the new 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