0

I am using gson 2.8 for serialization and deserialization I have OffsetDateTime field in my class when I give the value "orderTime":"2018-05-02T14:23:00Z" I am getting it as "2018-05-02T14:23Z" where I am expecting "2018-05-02T14:23:00Z" if I give "orderTime":"2018-05-02T14:23:01Z" I am getting as expected "2018-05-02T14:23:00Z". Is there anyway to fix this issue?

Here is my Order Class

import com.google.gson.annotations.SerializedName;
import java.time.OffsetDateTime;
public class Order {
    @SerializedName("orderId")
    private String orderId = null;

    @SerializedName("orderType")
    private String orderType = null;

    @SerializedName("orderTime")
    private OffsetDateTime orderTime = null;
    ....
}
user1653027
  • 789
  • 1
  • 16
  • 38
  • I don't even see how Gson serializes `OffsetDateTime` to a simple string without something like [gson-javatime-serialisers](https://github.com/gkopff/gson-javatime-serialisers) as mentioned in https://stackoverflow.com/questions/23072733/how-to-serialize-and-deserialize-java-8s-java-time-types-with-gson – Miserable Variable Mar 25 '19 at 00:38

1 Answers1

2

Is there anyway to fix this issue?

There isn’t any fix. The question is whether there is an issue at all.

2018-05-02T14:23:00Z and 2018-05-02T14:23Z denote the same point in time. When the seconds are 0 as here, they are optional in the format. The format is called ISO 8601. So you have got the value that you expected.

The string you see is produced by OffsetDateTime.toString(). There is no way to modify the working of this method (not even by overriding since OffsetDateTime is a final class).

There is a fix for seeing another string, though. Use a formatter:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXXXX");
    System.out.println(orderTime.format(formatter));

This prints:

2018-05-02T14:23:00Z

Link: Wikipedia article on ISO 8601

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161