gpt4 book ai didi

java - 如何从 TemporalAccessor 获取 ZoneId、LocalDateTime 和 Instant

转载 作者:行者123 更新时间:2023-11-29 04:07:44 28 4
gpt4 key购买 nike

我正在使用下面的代码来解析日期字符串:

    String time = "2 Jun 2019 03:51:17 PM ACST";
String pattern = "d MMM yyyy hh:mm:ss a z"; // z detects the time zone (ACST here)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);

// ZonedDateTime localDateTime = LocalDateTime.from(formatter.parse(time)).atZone(ZoneId.of("Australia/Adelaide"));
// localDateTime.toInstant().toEpochMilli();

当我通过调试检查时,formatter.parse(time) 已经有了纪元时间和时区:

// formatter.parse(time) :
{InstantSeconds=1559456477},ISO,Australia/Adelaide resolved to 2019-06-02T15:51:17

我的问题是如何从 formatter.parse(time) 中提取时区(这里是 Australia/Adelaide),它是 Parsed 类型,以便在中动态使用时区atZone() 在这一行? :

ZonedDateTime localDateTime = LocalDateTime.from(formatter.parse(time)).
atZone(ZoneId.of("Australia/Adelaide"));

甚至 Furthur,如何从 formatter.parse(time) 响应中提取 InstantSeconds=1559456477 以避免采取以下更多步骤来获取纪元时间戳? :

ZonedDateTime localDateTime = LocalDateTime.from(formatter.parse(time)).
atZone(ZoneId.of("Australia/Adelaide"));

localDateTime.toInstant().toEpochMilli();

最佳答案

DateTimeFormatter.parse 方法返回 TemporalAccessor其中包含日期、时间和一些其他信息,您可以通过查询获取该信息

default <R> R query(TemporalQuery<R> query)

Framework-level interface defining read-only access to a temporal object, such as a date, time, offset or some combination of these.

This is the base interface type for date, time and offset objects. It is implemented by those classes that can provide information as fields or queries.

TemporalQuery是功能接口(interface)

The most common implementations are method references, such as LocalDate::from and ZoneId::from. Additional common queries are provided as static methods in TemporalQueries.

String time = "2 Jun 2019 03:51:17 PM ACST";
String pattern = "d MMM yyyy hh:mm:ss a z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);

TemporalAccessor parsedTime = formatter.parse(time);

ZoneId zone = parsedTime.query(ZoneId::from);

LocalDateTime localDateTime = parsedTime.query(LocalDateTime::from);

Instant instant = parsedTime.query(Instant::from);

System.out.println(zone);
System.out.println(localDateTime);
System.out.println(instant);

关于java - 如何从 TemporalAccessor 获取 ZoneId、LocalDateTime 和 Instant,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57265780/

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