Cannot convert String to Date

Guided by this article, I managed to convert the date where days / months / years are transferred in numbers, but when, for example, I enter the name of the month in letters, an error occurs

Works:

SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy");//задаю формат даты String dateInString = "29 11 2015";//создаю строку по заданному формату Date date = formatter.parse(dateInString);//создаю дату через System.out.println(formatter.format(date)); 

Does not work:

 SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy"); String dateInString = "28-Nov-2015"; Date date = formatter.parse(dateInString); System.out.println(formatter.format(date)); 

Gives out:

 Exception in thread "main" java.text.ParseException: Unparseable date: "28-Nov-2015" 

    2 answers 2

    Java attempts to use regional settings taken from the system. And there, most likely, Russian is used. In order for the parser to understand the English names of the months, it must be created a little differently:

     new SimpleDateFormat("dd-MMM-yyyy", Locale.US); 

    Or write the names of the months in Russian:

     String dateInString = "28-Ноя-2015"; 
    • thanks, helped - Ildar
      public static String dateToString(Date date, String f) { if (date != null) { return new SimpleDateFormat(f, Locale.ENGLISH).format(date); } return null; }