【问题标题】:Java short date String convert to ZonedDateTime [duplicate]Java短日期字符串转换为ZonedDateTime [重复]
【发布时间】:2021-11-25 14:46:50
【问题描述】:

我有一个String,其日期格式为:2021-10-05。需要将此String 转换为ZonedDateTime 类型。尝试以这种方式进行操作,但无法解析 Text。时间可以是 00:00:00。有什么建议吗?

public static final ZoneId ZONE_ID = ZoneId.of("UTC");

ZonedDateTime dt2 = ZonedDateTime.parse(date, //date String = 2021-10-05
DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZONE_ID));

【问题讨论】:

  • 你的意思是把 3 个Ms 放在那里吗?应该只有 2 个。
  • 哦...是的,应该有 2 个M。问题不在于M。已编辑。使用此代码我收到错误:Text '2021-10-05' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO,UTC resolved to 2021-10-05 of type java.time.format.Parsed
  • 提示:将您的异常消息粘贴到您的搜索引擎中。它比在这里等待答案要快得多。

标签: java date type-conversion zoneddatetime


【解决方案1】:

现代日期时间 API 基于 ISO 8601,只要日期时间字符串符合 ISO 8601 标准,就不需要明确使用 DateTimeFormatter 对象。

由于您的日期字符串已经是 ISO 8601 格式,您可以简单地将其解析为 LocalDate 而不需要 DateTimeFormatter,然后您可以使用 LocalDate#atStartOfDay(ZoneId) 将解析后的值转换为 ZonedDateTime

演示:

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        ZonedDateTime zdt = LocalDate.parse("2021-10-05").atStartOfDay(ZoneId.of("UTC"));
        System.out.println(zdt);
    }
}

输出:

2021-10-05T00:00Z[UTC]

ONLINE DEMO

通过 Trail: Date Time 了解有关 modern Date-Time API* 的更多信息。


* 如果您正在为一个 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring。请注意,Android 8.0 Oreo 已经提供了support for java.time

【讨论】:

    【解决方案2】:

    您必须先使用LocalDate 转换,因为在给定字符串中没有时间进行解析:

    LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    ZonedDateTime dt2 = ZonedDateTime.of(localDate, LocalTime.MIDNIGHT, ZONE_ID);
    

    或者以更优雅的方式发布在 cmets 中:

    LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    ZonedDateTime dt2 = localDate.atStartOfDay(ZONE_ID);
    

    【讨论】:

      猜你喜欢
      • 2011-08-30
      • 2017-11-20
      • 1970-01-01
      • 2023-03-30
      • 2011-06-08
      • 1970-01-01
      • 2011-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多