首页 > 解决方案 > 正确的日期格式用于 GsonBuilder 日期格式

问题描述

我的客户以“2019-11-22T16:16:31.0065786+00:00”格式向我发送日期。我收到以下错误:

java.text.ParseException:无法解析的日期:“2019-11-22T16:16:31.0065786+00:00”

我使用的日期格式是:

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

请让我知道使用哪种格式。

标签: javadategsondate-formatdate-parsing

解决方案


这种格式可以由DateTimeFormatter.ISO_ZONED_DATE_TIME的实例处理DateTimeFormatter。它是与版本Java Time一起发布的包的一部分。1.8您应该使用ZonedDateTime来存储这样的值,但我们也可以将其转换为过时的Date类。

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 +
                '}';
    }
}

上面的代码打印:

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

当您更改ZonedDateTime为上课时DateDateValue它将打印与您的时区相关的日期。

也可以看看:


推荐阅读