本文介绍了将字符串时间戳解析为Instant throws不支持的字段:InstantSeconds的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将String转换为Instant.你能帮我吗?

I am trying to convert a String into an Instant. Can you help me out?

我收到以下异常:

我的代码基本上是这样的

My code looks basically like this

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String timestamp = "2016-02-16 11:00:02";
TemporalAccessor temporalAccessor = formatter.parse(timestamp);
Instant result = Instant.from(temporalAccessor);

我正在使用Java 8 Update 72.

I am using Java 8 Update 72.

推荐答案

以下是获取具有默认时区的Instant的方法.您的字符串无法直接解析为Instant,因为缺少时区.因此,您始终可以获取默认的

Here is how to get an Instant with a default time zone. Your String can not be parsed straight to Instant because timezone is missing. So you can always get the default one

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

String timestamp = "2016-02-16 11:00:02";
TemporalAccessor temporalAccessor = formatter.parse(timestamp);
LocalDateTime localDateTime = LocalDateTime.from(temporalAccessor);
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());
Instant result = Instant.from(zonedDateTime);

这篇关于将字符串时间戳解析为Instant throws不支持的字段:InstantSeconds的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 09:20