【发布时间】:2019-09-23 08:15:56
【问题描述】:
我的客户以 ISO8601 格式向我发送日期,其中有时包含带区域的毫秒,有时不包含毫秒和区域。
例如:2019-05-01T06:55:43+01:00, 2019-05-01T06:55
我正在使用新的 Java 8 API(LocalDateTime、DateTimeFormatter 等)。
我没有找到带有格式化程序的Date 类,它可以同时处理毫秒和区域,而没有这个。
我正在尝试使用单一格式进行输入日期验证
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(templateFormat, locale);
try {
ldt = LocalDateTime.parse(context, formatter );
String result = ldt.format(formatter);
return result.equals(context);
} catch (DateTimeParseException e) {
try {
LocalDate ld = LocalDate.parse(context, formatter );
String result = ld.format(formatter);
return result.equals(context);
我在问是否有一个格式化器可以同时缓存两者,我可以使用多个日期类,如果我失败继续下一个,例如(LocalDateTime、LocalDate、OffsetDateTime)但我需要使用一个格式化器
【问题讨论】:
-
你想如何处理每一个?我的意思是因为它们不包含相同的信息。
-
这很相似,但不一样:How to parse different ISO date/time formats with Jackson and java.time?(不处理没有任何 UTC 偏移量的格式,只处理该 UTC 偏移量的不同格式)。
-
这是您第一次输入时的 UTC 偏移量,而不是区域。时区有一个名称,例如
Africa/Casablanca,而不仅仅是小时-分钟-秒数。时区是特定地区的人们使用的偏移量的过去、现在和未来变化的历史。 -
不过,你仍然让我感到困惑。我现在明白这是为了验证,但您对有效或无效日期时间字符串的准确标准是什么?