首页 > 解决方案 > 更改会话语言会导致“java.text.ParseException: Unparseable date

问题描述

每当我在更改为英语语言后以德语会话语言定义时间范围时。会话(反之亦然)我得到: java.text.ParseException: Unparseable date: "10.10.2018"

这是片段:

    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);
        }
    }

标签: datetimeparsingparseexceptionjava-calendarunparseable

解决方案


java.time

我建议您使用现代 Java 日期和时间 API java.time 进行日期工作。

    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);

输出:

2018-10-10

如果您想为不同的语言环境支持不同的日期格式,让 Java 为您处理这部分:

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

德语语言环境适用于您的示例字符串10.10.2018. 例如,对于英国语言环境,10 Oct 2018就像英国人通常期望的那样,需要一个类似的字符串。

你的代码出了什么问题?

我们无法从您提供的信息和代码中确切地看出发生了什么。几个不错的猜测是:

  1. 正如 Arvind Kumar Avinash 在评论中所说,getLocalizedString()可能会造成麻烦。您可以打印datePattern检查。本地化是您对显示给用户的字符串所做的事情。尝试为格式化程序本地化格式模式字符串可能是完全错误的,因此您应该省略该方法调用。更改语言时发生错误似乎支持这种可能性。
  2. 您的字符串中可能有意外的非打印字符。检查的一种方法是打印startDate.length(). 如果长度大于 10,则字符数超过 10 个字符10.10.2018

关联

Oracle 教程:日期时间解释如何使用 java.time。


推荐阅读