java.time and ThreeTen Backport
This works on Java 7 (details below):
DateTimeFormatter jsonDateFormatter = DateTimeFormatter.ofPattern("uuuu-MMM-dd", Locale.ENGLISH);
DateTimeFormatter outputDateFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
String pDate = "2011-Jan-01";
LocalDate fDate = LocalDate.parse(pDate, jsonDateFormatter);
pDate = fDate.format(outputDateFormatter);
System.out.println("Formatted date: " + pDate);
Output from the snippet is:
Formatted date: 01-01-2011
Unless you have strong reasons not to, I recommend that you use one of Java’s built-in formats for your user’s locale rather than hardcoding an output format. For example:
DateTimeFormatter outputDateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.UK);
Now the output is:
Formatted date: 01-Jan-2011
Question: Why java.time?
The old datetime classes that you tried to use in the question, Date
and SimpleDateFormat
are poorly designed, the latter notoriously troublesome. Fortunately they are also long outdated. java.time, the modern Java date and time API, is so much nicer to work with.
Question: Can I use java.time on Java 7? How?
Yes, java.time works nicely on Java 7. 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