Java 将字符串时间戳解析为 Instant 抛出不支持的字段:InstantSeconds
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35610597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parse String timestamp to Instant throws Unsupported field: InstantSeconds
提问by keiki
I am trying to convert a String into an Instant. Can you help me out?
我正在尝试将字符串转换为 Instant。你能帮我吗?
I get following exception:
我得到以下异常:
Caused by: java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: InstantSeconds at java.time.format.Parsed.getLong(Parsed.java:203) at java.time.Instant.from(Instant.java:373)
引起: java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: InstantSeconds at java.time.format.Parsed.getLong(Parsed.java:203) at java.time.Instant.from(Instant.java:373)
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);
I am using Java 8 Update 72.
我正在使用 Java 8 Update 72。
采纳答案by Michael Gantman
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
以下是如何获得具有默认时区的 Instant 。由于缺少时区,您的字符串无法直接解析为 Instant。所以你总是可以得到默认的
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);
回答by jdex
A simpler method is to add the default timezone to the formatter object when declaring it
一个更简单的方法是在声明它时将默认时区添加到格式化程序对象
final DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.systemDefault());
Instant result = Instant.from(formatter.parse(timestamp));
回答by Parthiban
First convert your date into util date using date format as you don't have time zone in your input. Then you can convert that date into Instant date. This will give you date with accurate time.
首先使用日期格式将您的日期转换为 util 日期,因为您的输入中没有时区。然后您可以将该日期转换为即时日期。这将为您提供准确时间的日期。
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timestamp = "2016-02-16 11:00:02";
Date xmlDate = dateFormat.parse(timestamp);
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Instant instantXmlDate = Instant.parse(dateFormat.format(xmlDate));