0

尝试从日期字符串解析 ZonedDateTime,例如“2020-08-24”。

在使用 TemporalAccesor 和 DateTimeFormatter.ISO_OFFSET_DATE 进行解析时,我得到一个 java.time.format.DateTimeParseException。我使用了错误的格式化程序吗?

甚至尝试在日期字符串的末尾添加“Z”以将其理解为 UTC

private ZonedDateTime getZonedDateTime(String dateString) {
  TemporalAccessor parsed = null;
  dateString = dateString + 'Z';
  try {
     parsed = DateTimeFormatter.ISO_OFFSET_DATE.parse(dateString);
  } catch (Exception e) {
     log.error("Unable to parse date {} using formatter DateTimeFormatter.ISO_INSTANT", dateString);
  }
  return ZonedDateTime.from(parsed);
}

4

3 回答 3

4

利用LocalDate#atStartOfDay

执行以下操作:

import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // Define a DateTimeFormatter
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd");

        // Given date string
        String strDate = "2020-08-24";

        // Parse the given date string to ZonedDateTime
        ZonedDateTime zdt = LocalDate.parse(strDate, dtf).atStartOfDay(ZoneOffset.UTC);

        System.out.println(zdt);
    }
}

输出:

2020-08-24T00:00Z
于 2020-09-24T11:39:02.960 回答
1

正如评论部分链接的帖子中提到的:

问题是ZonedDateTime需要构建所有日期和时间字段(年、月、日、小时、分钟、秒、纳秒),但格式化程序 ISO_OFFSET_DATE 会生成一个没有时间部分的字符串。

以及相关的解决方案

解析它的一种替代方法是使用 aDateTimeFormatterBuilder并为时间字段定义默认值

于 2020-09-24T10:59:18.807 回答
0

ISO_OFFSET_DATE 中的偏移量表示时区被指定为相对于 UTC 的相对偏移量

因此,在您输入的末尾应该会出现类似“+01:00”的内容。

于 2020-09-24T11:05:51.457 回答