Abdul
Abdul

Reputation: 21

Correct Date format to use for GsonBuilder Date Format

My client sends me a date in "2019-11-22T16:16:31.0065786+00:00" format. I am getting the following error:

java.text.ParseException: Unparseable date: "2019-11-22T16:16:31.0065786+00:00"

The date format that I am using is:

new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ")
    .create();

Please let me know which format to use.

Upvotes: 2

Views: 2972

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38655

This format can be handled by DateTimeFormatter.ISO_ZONED_DATE_TIME instance of DateTimeFormatter. It is a part of Java Time package which was released together with 1.8 version. You should use ZonedDateTime to store values like this but we can convert it also to obsolete Date class.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;
import java.time.ZonedDateTime;
import java.util.Date;

public class GsonApp {

    public static void main(String[] args) {
        Gson gson = new GsonBuilder()
                .setPrettyPrinting()
                .registerTypeAdapter(Date.class, new DateJsonDeserializer())
                .registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeJsonDeserializer())
                .create();

        System.out.println(gson.fromJson("{\"value\":\"2019-11-22T16:16:31.0065786+00:00\"}", DateValue.class));
    }
}

class DateJsonDeserializer implements JsonDeserializer<Date> {
    @Override
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        ZonedDateTime zdt = ZonedDateTime.parse(json.getAsString());

        return Date.from(zdt.toInstant());
    }
}

class ZonedDateTimeJsonDeserializer implements JsonDeserializer<ZonedDateTime> {
    @Override
    public ZonedDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return ZonedDateTime.parse(json.getAsString());
    }
}

class DateValue {
    private ZonedDateTime value;

    public ZonedDateTime getValue() {
        return value;
    }

    public void setValue(ZonedDateTime value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "DateValue{" +
                "value=" + value +
                '}';
    }
}

Above code prints:

DateValue{value=2019-11-22T16:16:31.006578600Z}

When you change ZonedDateTime to Date in DateValue class it will print this date with relation to your time zone.

See also:

Upvotes: 1

Related Questions