java.time through desugaring or ThreeTenABP
I recommend that you consider java.time, the modern Java date and time API, for your date work.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String textFromEditText = "23-08-2013";
LocalDate myDate = LocalDate.parse(textFromEditText, dateFormatter);
String myText = myDate.format(dateFormatter);
System.out.println("Formatted again: " + myText);
Output is:
Formatted again: 23-08-2013
Just as you use a formatter for parsing a string to a LocalDate
, also use a formatter when formatting the ohter way, from a LocalDate
to a String
. And if you want the same format again, just use the same formatter again.
What went wrong in your code?
The Date
class is poorly designed and often confusing. The answer by Ken Wolf is correct about the confusing behaviour of the methods that have been deprecated since Java 1.1 (February 1997).
There is one more problem in your code, the use of uppercase YYYY
in your format pattern string. Uppercase YYYY
is for week based year and only useful with a week number. Lower case yyyy
is for year of era. In fact, because of this error I got 1-11-112abcd
from your code, which is still further off than the result that you reported. All three numbers are incorrect.
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 either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links