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

标签 java parsing time

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

    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/

相关文章:

java - 'com.itextpdf.text.exceptions.InvalidPdfException : PDF header signature not found' when reading the input stream from servlet

javascript - 拆分字符串包括正则表达式匹配

c++ - 两个日期之间的秒数差异?

c - 试图找到一个完全随机数生成器

java - 在二维数组的 IF 语句中使用 AND OR 来对行的值求和

java - Spring 管理的事务未启动

java - 如何格式化 Velocity 模板中的数字?

python - Python 中灵活的数字字符串解析

php - 如何使用 PHP 将文本文件(CSV)解析到 MySQL 中

javascript - 如何使用 javascript 获取最后一整天的时间戳