Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

How can I convert from String to Date in JAVA without changing the offset?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
217 views
Welcome To Ask or Share your Answers For Others

1 Answer

java.util.Date doesn't store time zone information.

To retain time zone, use ZonedDateTime or OffsetDateTime (Java 8+).

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

For pre-Java 8, use the ThreeTen-Backport:

ThreeTen-Backport provides a backport of the Java SE 8 date-time classes to Java SE 6 and 7.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...