java.time
The java.util
date-time API and their corresponding parsing/formatting type, SimpleDateFormat
are outdated and error-prone. In March 2014, the modern Date-Time API was released as part of the Java 8 standard library which supplanted the legacy date-time API and since then it is strongly recommended to switch to java.time
, the modern date-time API.
Solution using java.time
*
The java.time
API is based on ISO 8601 standards and does not require specifying a DateTimeFormatter
to parse a date/time string which is already in ISO 8601 format. Your given date string, 2013-06-24
is already in ISO 8601 format. You need a DateTimeFormatter
just for formatting the LocalDate
which will be obtained by parsing the given date string.
Note: The date-time parsing/formatting APIs are Locale
sensitive and therefore never use date-time parsing/formatting APIs without a Locale.
Demo:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.parse("2013-06-24");
System.out.println(date);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM uuuu", Locale.ENGLISH);
String formatted = date.format(formatter);
System.out.println(formatted);
}
}
Output:
2013-06-24
24 Jun 2013
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
* If you are working on an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.