DateTimeFormatter enteredFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
DateTimeFormatter usDateFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.US);
LocalDate d;
try {
d = LocalDate.parse(date.getText(), enteredFormatter);
System.out.println(d.format(usDateFormatter));
} catch (DateTimeParseException dtpe) {
Toast.makeText(MainActivity.this,
"Date format is wrong.", Toast.LENGTH_LONG).show();
return;
}
Getting the incorrect dates from your question this code will catch a java.time.format.DateTimeParseException: Text '111/10/2013' could not be parsed at index 2
or java.time.format.DateTimeParseException: Text '11/109/2013' could not be parsed at index 5
and therefore give the error message to the user. Given a correct date string like 11/10/2013
it prints like:
Oct 11, 2013
A detail that I haven’t tested on Android: As I understand, EditText.getText
will return an Editable
, which implements CharSequence
. Since LocalDate.parse
accepts a CharSequence
, you can pass date.getText()
with no need for .toString()
.
When formatting a date for an audience, the first thing you should consider is using one of Java’s built-in formatters for that audience’s locale. Your requested format agrees with the MEDIUM
format for US locale. I took this to be no coincidence. So do take advantage.
At the same time I am taking advantage of java.time
, the modern Java date and time API. SimpleDateFormat
is notoriously troublesome and long outmoded. I avoid it. The modern API is so much nicer to work with.
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