Changing the Session Languge leads to "java.text.ParseException: Unparseable date

65 views Asked by At

whenever I'm defining the timeframe being in German session language after changing to English lang. session (and vice versa) I'm getting the: java.text.ParseException: Unparseable date: "10.10.2018"

Here is the fragment:

    Date startDateFormatted = DateUtils.convertDateToMinusDayNumber(cal, dayRange);
    Date endDateFormatted = new Date();

    if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate))
    {
        try
        {
            String datePattern = getLocalizedString("dd.MM.yyyy"); // 
            startDateFormatted = new SimpleDateFormat(datePattern).parse(startDate); // exception is throwing on this line
            endDateFormatted = new SimpleDateFormat(datePattern).parse(endDate);
        }
        catch (final Exception e)
        {
            LOG.error(ERROR_DATE_PARSING, e);
        }
    }
1

There are 1 answers

0
Anonymous On

java.time

I recommend you use java.time, the modern Java date and time API, for your date work.

    String datePattern = "dd.MM.uuuu";
    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(datePattern);
    
    String startDateString = "10.10.2018";
    
    LocalDate startDate = LocalDate.parse(startDateString, dateFormatter);
    
    System.out.println(startDate);

Output:

2018-10-10

If you want to support different date formats for different locales, let Java handle that part for you:

    String datePattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
            FormatStyle.MEDIUM, null, IsoChronology.INSTANCE, Locale.GERMAN);

German locale works with your example string of 10.10.2018. For UK locale, for example, a string like 10 Oct 2018 would be required instead, as Britons would typically expect.

What went wrong in your code?

We cannot tell from the information and code that you have provided exactly what happened. A couple of good guesses are:

  1. As Arvind Kumar Avinash said in a comment, getLocalizedString() may be causing trouble. You may print datePattern to check. Localization is something you do to strings that you display to the user. Trying to localize a format pattern string for a formatter is probably plain wrong, so you should leave out that method call. That the error occurs when changing language seems to support this possibility.
  2. There may be unexpected non-printing characters in your string. One way to check would be to print startDate.length(). If the length is greater than 10, there are more characters than the 10 chars in 10.10.2018.

Link

Oracle tutorial: Date Time explaining how to use java.time.