java.time and ThreeTenABP
This will give you the output that you asked for, 2019-07-23
(with correct month number, 07, and with leading zero):
onDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
LocalDate date = LocalDate.of(year, month + 1, dayOfMonth);
String dateString = date.toString();
System.out.println(dateString);
}
};
I am using LocalDate
from java.time, the modern Java date and time API. We need to add one to the month because DatePicker
confusingly counts months from 0 for January through 11 for December, while LocalDate
numbers months the same way humans do. LocalDate.toString()
produces the yyyy-MM-dd
format you asked for. It conforms with ISO 8601.
What went wrong in your code?
First because, as mentioned, DatePicker
numbers months from 0, you got the wrong month, 6 for July, so it was printed as June in your output. Second, formatting the date into a string, parsing it into a Date
and printing that Date
as a string is over-complicating things. Also Date.toString()
always produces the format you saw, EEE MMM dd HH:mm:ss zzz yyyy
. To produce a different string from that you would have needed to format it explicitly.
In any case both SimpleDateFormat
and Date
are poorly designed and long outdated. And the modern date and time API is so much nicer to work with. I recommend it warmly.
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