Search code examples
javasimpledateformatjava-timedayofweekdatetime-parsing

java.text.ParseException: Unparseable date : "..."


I get this error with this code:

SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd MMMM HH:mm yyyy",myDateFormatSymbols);
sdf.parse("понеділок 12 квітень 07:00 2021");

Whis is "Monday 12 April 07:00 2021". The thing is, whenever I change the day from Monday to Tuesday ("вівторок"), I don't get this error, and the code works. Here's the code for myDateFormatSymbols:

private final static DateFormatSymbols myDateFormatSymbols = new DateFormatSymbols(){
        @Override
        public String[] getWeekdays(){
             return new String[]{"понеділок","вівторок", "середа", "четвер", "пятниця", "субота", "неділя"};
        }
        @Override
        public String[] getMonths() {
            return new String[]{...};
        }
}

All the months and weekdays are working correctly, seems that this error only occurs with Monday.


Solution

  • You can check the Javadoc for DateFormatSymbols#weekdays, the element at index 0 is always ignored unfortunately.

    I'd simply replace it by an empty string.

    Weekday strings. For example: "Sunday", "Monday", etc. An array of 8 strings, indexed by Calendar.SUNDAY, Calendar.MONDAY, etc. The element weekdays[0] is ignored.


    The following code now prints the expected answer

    DateFormatSymbols myDateFormatSymbols = new DateFormatSymbols() {
        @Override
        public String[] getWeekdays() {
            return new String[]{"", "понеділок", "вівторок", "середа", "четвер", "пятниця", "субота", "неділя"};
        }
    
        @Override
        public String[] getMonths() {
            return new String[]{"квітень"};
        }
    };
    
    SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd MMMM HH:mm yyyy", myDateFormatSymbols);
    System.out.println(sdf.parse("понеділок 12 квітень 07:00 2021")); // Tue Jan 12 07:00:00 CET 2021