I'm using JSON-B (yasson implementation) and I'm receiving data for an object with a field like this
{
...
"timestamp": "2020-03-19T06:42:42Z",
...
}
which is perfectly standard ISO 8601 for a UTC date-time value. Now the corresponding Java class simply declares a Date member variable with no other specific annotation
...
private Date timestamp;
...
everything seems to work fine and it looks like the JSON-B implementation correctly understands that as UTC without me having to specify a format using the @JsonbDateFormat annotation. I think I'm sure of it because I checked with
ZonedDateTime datetimeCheck = ZonedDateTime.of(2020, 3, 19, 6, 42, 42, 0, ZoneId.of("UTC"));
Date parsedDateFromJson = myModel.getTimestamp();
boolean compareTs = parsedDateFromJson.equals(Date.from(datetimeCheck.toInstant()));
and it yields true however, when I ran another test removing the 'Z' from the date-time value I was expecting it to produce a different result interpreting the date-time value as local rather than UTC. With my great surprise, the Date object obtained by JSON-B was exactly the same. What am I missing here? Why are 2020-03-19T06:42:42Z and 2020-03-19T06:42:42 the same thing? (I don't think they are). Or maybe is the JSON-B implementation considering UTC as default always when no timezone is specified?
Thanks
Or maybe is the JSON-B implementation considering UTC as default always when no timezone is specified?
Exactly this. Contrary to what its name implies, a java.util.Date
actually doesn't represent a date but an instant in time. Specifically, it represents the number of milliseconds since UNIX epoch (January 1, 1970, 00:00:00 GMT).
2020-03-19T06:42:42
is a date + time without zone or offset information. When deserializing this date + time to a java.util.Date
, i.e. an instant in time, you need to decide how to interpret the date + time. Is this the date + time at UTC? Is this the date + time in your local timezone?
Luckily for us, the JSON-B specification contains the following: "If not specified otherwise in this section, GMT standard time zone and offset specified from UTC Greenwich is used." As this statement shows, the authors made the choice of interpreting a date + time without timezone as a date + time at UTC.