Good day!

Tell me what could be the problem. I need to convert the pattern of the form "dd MMM yyyy" to LocalDate, but constantly throws out, on the one hand, a clear one, on the other - an incomprehensible "Text '16 Sep 2006 'could not be parsed at index 3".

import java.time.LocalDate; import java.time.format.DateTimeFormatter; ... String date1 = "16 Sep 2006"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM yyyy"); LocalDate dateLocal = LocalDate.parse(date1, formatter); 

I tried different variations of patterns, but always the same thing, it seems like it should work. : /

  • one
    Check your locale - it feels like it is expected 16 Сен 2006 September 16 Сен 2006 - index 3 - just shows the first character of the month - Barmaley
  • @Barmaley, hmm, an interesting idea, but a similar result from index 3. - Ilja
  • 16 сен 2006 Sep with a lowercase letter - cadmy
  • @cadmy, not a friend, this option also does not go. - Ilja

1 answer 1

After some research, it turned out that in the case of DateTimeFormatter, in addition to the template, you also need to specify the formatting style, if the line contains the letter symbols of the month or day. It is also important to note that if the string is only in numeric form, then the formatting style can be omitted. These are the differences from the simple DateFormatter, where only a template is enough.

Thanks party Barmaley , brought the right thought about Locale.

Option 1 :

 java.util.Locale locale = java.util.Locale.US; String input = "January 2, 2010"; String pattern = "MMMM d, yyyy"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern,locale); LocalDate dateLocal = LocalDate.parse(input, formatter); 

Option 2 :

  String input = "16 Sep 2006"; String pattern = "dd MMM yyyy"; //Далее, как с Вариантом 1