解析字符串到日期,时区偏移量保持不变 [英] Parse String to date with timezone offset intact
问题描述
我们有一个客户以String格式("2017-06-14T04:00:00-08:00"
)向我们发送日期.在使用它之前,我们需要将其转换为JAVA Date类型.
We have a client sending date to us in String format as "2017-06-14T04:00:00-08:00"
. We need to convert it to JAVA Date type before working with it.
我们以这种方式进行解析:
We are parsing in this way:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
dateParsedFromString = formatter.parse("2017-06-14T04:00:00-08:00");
但是在解析之后我们失去了偏移量.当我们将其转换回字符串时,我们看到的是值:
But we are losing the offset after this parse. When we convert it back to string we are seeing value:
2017-06-14T08:00:00-04:00
2017-06-14T08:00:00-04:00
如何在不更改偏移量的情况下从JAVA中的 String
转换为 Date
?
How can I convert from String
to Date
in JAVA without changing the offset?
推荐答案
java.util.Date
不存储时区信息.
java.util.Date
doesn't store time zone information.
要保留时区,请使用 ZonedDateTime
或 OffsetDateTime
(Java 8 +).
To retain time zone, use ZonedDateTime
or OffsetDateTime
(Java 8+).
由于您的日期字符串为 ISO 8601 ,因此您甚至无需指定日期格式.
Since your date string is ISO 8601, you won't even need to specify a date format.
ZonedDateTime zdt = ZonedDateTime.parse("2017-06-14T04:00:00-08:00");
System.out.println(zdt); // prints: 2017-06-14T04:00-08:00
OffsetDateTime odt = OffsetDateTime.parse("2017-06-14T04:00:00-08:00");
System.out.println(odt); // prints: 2017-06-14T04:00-08:00
对于Java 8之前的版本,请使用 ThreeTen-Backport :
For pre-Java 8, use the ThreeTen-Backport:
ThreeTen-Backport将Java SE 8日期时间类的反向移植到Java SE 6和7.
ThreeTen-Backport provides a backport of the Java SE 8 date-time classes to Java SE 6 and 7.
这篇关于解析字符串到日期,时区偏移量保持不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!