我使用下面的代码来解析日期字符串:
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)
中提取时区(此处为澳大利亚/阿德莱德),该时区是 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/