Search code examples
javadate-formatting

Convert String into Date java


import java.text.DateFormat;
import java.text.ParseException; 
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatter {
    public static void main(String[] args) throws ParseException {       
        String testString = "14 September 11";
        DateFormat df = new SimpleDateFormat("dd MMMM yy");
        Date newDate = df.parse(testString); 
    }
}

Tell me, why do I have:

Exception in thread "main" java.text.ParseException: Unparseable date: "14 September 11"
    at java.text.DateFormat.parse(DateFormat.java:357)
    at com.testtask.ruslan.converter.DateFormatter.main(DateFormatter.java:17)

Solution

  • It will work for English locales, but for others languages it won't. Do not rely on default locale. You always should specify locale explicitly for such conversions:

    With Locale.US it passes:

        String testString = "14 September 11";
        DateFormat df = new SimpleDateFormat("dd MMMM yy", Locale.US);
        Date newDate = df.parse(testString);
    

    With new Locale("ru", "RU") it fails:

        String testString = "14 September 11";
        DateFormat df = new SimpleDateFormat("dd MMMM yy", new Locale("ru", "RU"));
        Date newDate = df.parse(testString);