格式字符串 2018-11-26T15:12:03.000-0800 到 java.time.localdateformat 的字符串"M/dd/yy HH:mm:ss a z"转换引发异常



我编写了一个util函数,将格式为2018-11-26T15:12:03.000-0800的字符串时间值转换为格式为"M/dd/yy HH:mm:ss a z"的localdatetime

格式为2018-11-26T15:12:03-0000-0800的字符串到格式为"M/dd/yy HH:mm:ss a z"的java.time.localdatetime转换引发异常。

public static LocalDateTime convertStringToTime(String time){
String pattern = "M/dd/yy HH:mm z";
DateTimeFormatter formatter =  DateTimeFormatter.ofPattern(pattern);
ZonedDateTime zonedDateTime = ZonedDateTime.parse(time,formatter);
return zonedDateTime.toLocalDateTime();
}

这给了我以下异常

java.time.format.DateTimeParseException: Text '2018-11-26T12:45:23.000-0800' could not be parsed at index 4
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1947)

您说您想要:M/dd/yy HH:mm:ss a z格式的LocalDateTime。这是不可能的,原因有三:

  1. LocalDateTime不能有格式。它的toString方法总是返回类似2018-11-26T15:12:03(ISO 8601格式(的字符串,我们无法更改这一点。您也不应该想要具有特定格式的LocalDateTime;我在底部添加了一个链接,解释为什么不这样做
  2. 我假设您的格式中的z是指时区缩写,如太平洋夏令时的PDTLocalDateTime既没有UTC偏移,也没有时区偏移,所以这没有意义
  3. 您的输入时间字符串也不包含任何时区,只包含与UTC的偏移量。因此,要打印时区缩写,您首先需要选择一个时区

相反,我建议:

ZoneId zone = ZoneId.of("America/Whitehorse");
DateTimeFormatter inputFormatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXX");
DateTimeFormatter desiredFormatter
= DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.LONG)
.withLocale(Locale.US);
String time = "2018-11-26T15:12:03.000-0800";
OffsetDateTime dateTime = OffsetDateTime.parse(time, inputFormatter);
String formattedDateTime = dateTime.atZoneSameInstant(zone)
.format(desiredFormatter);
System.out.println("Converted format: " + formattedDateTime);

输出为:

转换格式:11/26/18,太平洋标准时间下午3:12:03

要将日期和时间从一种格式的字符串转换为另一种格式,通常需要两个DateTimeFormatter:一个指定您所获得的字符串的格式,另一个指定所需的格式。

与其从格式模式字符串构建自己的格式化程序,不如尽可能使用内置格式。在我们的例子中,我指定FormatStyle.SHORT作为日期(给出两位数的年份(,指定FormatStyle.LONG作为时间,给出时区缩写。

依赖内置格式的想法可以更进一步。你得到的字符串是ISO 8601格式的,所以我们只需要把两部分拼凑在一起:

DateTimeFormatter inputFormatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.appendOffset("+HHmm", "Z")
.toFormatter();

它更长,但不太容易出错。

链接

  • 维基百科文章:ISO8601
  • 我对的回答是希望当前日期和时间为"dd/MM/yyyy HH:MM:ss.ss"格式,解释了为什么不希望使用具有格式的日期-时间对象

相关内容

最新更新