gpt4 book ai didi

java - 格式化分区日期时间

转载 作者:行者123 更新时间:2023-12-02 01:46:26 28 4
gpt4 key购买 nike

我需要将 ZonedDate 时间格式化为 MM/dd/yyyy

ZonedDateTime zonedDateTime = ZonedDateTime.now();
String date = DateTimeFormatter.ofPattern("MM/dd/yyyy").format(zonedDateTime);
ZonedDateTime zoneDate = ZonedDateTime.parse(date);

出现错误:

Exception in thread "main" java.time.format.DateTimeParseException: Text '12/05/2018' could not be parsed at index 0

或者,如果我将值转换为具有我想要的格式的字符串,然后尝试再次使用我的格式将其解析回 ZonedDate 时间:

DateTimeFormatter format = DateTimeFormatter.ofPattern("MM/dd/yyyy");
ZonedDateTime zonedDateTime = ZonedDateTime.now();
String date = DateTimeFormatter.ofPattern("MM/dd/yyyy").format(zonedDateTime);
ZonedDateTime zonedate = ZonedDateTime.parse(date, format);

我收到错误:

Exception in thread "main" java.time.format.DateTimeParseException: Text '12/05/2018' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 2018-12-05 of type java.time.format.Parsed

我已经看到很多关于此的问题,但我不断收到这些解析错误

最佳答案

有两个问题。首先,日期中没有区域信息,其次,没有时间信息。您可以将其转换为 LocalDate:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
ZonedDateTime zonedDateTime = ZonedDateTime.now();
String date = formatter.format(zonedDateTime);
LocalDate localdate = LocalDate.parse(date, formatter);

您还可以将 LocalDate 转换为 ZonedDateTime,方法是将时间设置为一天开始的时间,并将区域设置为默认系统区域。否则,您需要提供您选择的时间和 ZoneId

ZonedDateTime zdt = localdate.atStartOfDay(ZoneId.systemDefault());

关于java - 格式化分区日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53640120/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com