java.time
The date-time parsing/formatting types (the legacy, SimpleDateFormat
and the modern, DateTimeFormatter
) are Locale
-sensitive. Your date string, 09-Feb-13
is in English and therefore, if you try to parse it on a JVM which has a non-English Locale
set, your code will end up throwing an exception or giving you a wrong result (SimpleDateFormat
is notorious in this regard for silently parsing/formatting erroneous data with wrong results).
Since the legacy date-time API (java.util
date-time types and their formatting API, SimpleDateFormat
) is outdated and error-prone, it is recommended to stop using them completely and switch to java.time
, the modern date-time API*.
Demo using modern date-time API:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yy", Locale.ENGLISH);
LocalDate date = LocalDate.parse("09-Feb-13", dtf);
System.out.println(date);
}
}
Output:
2013-02-09
In case you need an object of java.util.Date
, you can get the same from this object of LocalDate
as shown below:
Date utilDate = Date.from(date.atStartOfDay(ZoneOffset.UTC).toInstant());
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for 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.