-1

I am trying to convert a date in java, but I am missing something. After spent several hours in this I couldn't figure out the solution:

SimpleDateFormat formatter2 = new SimpleDateFormat("dd-MMM-yy");
Date date2 =  formatter2.parse("09-Feb-13");  // throws error!
System.out.println(date2);
guilhermecgs
  • 2,913
  • 11
  • 39
  • 69

2 Answers2

4

If you don't provide a Locale to the formatter, it uses your default one which apparently doesn't spell months in English.

SimpleDateFormat(String pattern)

Constructs a newSimpleDateFormatusing the specified non-localized pattern and theDateFormatSymbolsandCalendarfor the user's default locale.

Specify one that does :

SimpleDateFormat formatter2 = new SimpleDateFormat("dd-MMM-yy", Locale.UK);
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
0

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110