datetime - 更改会话语言会导致“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);
}
}
解决方案
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
就像英国人通常期望的那样,需要一个类似的字符串。
你的代码出了什么问题?
我们无法从您提供的信息和代码中确切地看出发生了什么。几个不错的猜测是:
- 正如 Arvind Kumar Avinash 在评论中所说,
getLocalizedString()
可能会造成麻烦。您可以打印datePattern
检查。本地化是您对显示给用户的字符串所做的事情。尝试为格式化程序本地化格式模式字符串可能是完全错误的,因此您应该省略该方法调用。更改语言时发生错误似乎支持这种可能性。 - 您的字符串中可能有意外的非打印字符。检查的一种方法是打印
startDate.length()
. 如果长度大于 10,则字符数超过 10 个字符10.10.2018
。
关联
Oracle 教程:日期时间解释如何使用 java.time。
推荐阅读
- linux-kernel - RPi4:设备驱动程序 - 微秒延迟/计数
- javascript - 如何在循环的每次迭代中执行promise.then?Javascript
- ios - 根据在多选集合视图上选择的集合视图单元格显示不同的表视图数据
- c# - 如何序列化 Dynamics CRM 元数据
- java - 在 JUnit 或 TestNG 中的两个测试类之间共享一个对象
- azure - 从 Azure Active Directory 创建的租户是否完全独立?
- grep - 具有至少一个匹配值和至少一个不匹配的 Grep
- iframe - Headless Moodle:Iframe 身份验证
- python - 从python中的字典列表中获取最大值字典
- python - xlsxwriter:根据数据框排序值创建多个工作表