我正在使用下面的代码来解析日期字符串:
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
我的问题是如何从Parsed
类型的formatter.parse(time)
中提取时区(此处为Australia/Adelaide),以便在此行中的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
方法返回时间访问器,其中包含日期,时间和一些其他信息,您可以通过查询获得该信息
default <R> R query(TemporalQuery<R> query)
定义read-only对时间对象(例如日期,时间,偏移量或它们的某种组合)的访问的Framework-level接口。
这是日期,时间和偏移量对象的基本接口类型。它由可以提供字段或查询信息的类实现。
时间查询是功能接口
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);