【问题标题】:Correct Date format to use for GsonBuilder Date Format正确的日期格式用于 GsonBuilder 日期格式
【发布时间】:2019-11-22 18:29:31
【问题描述】:

我的客户以“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();

请告诉我要使用哪种格式。

【问题讨论】:

标签: java date gson date-format date-parsing


【解决方案1】:

此格式可以由DateTimeFormatterDateTimeFormatter.ISO_ZONED_DATE_TIME 实例处理。它是与1.8 版本一起发布的Java Time 包的一部分。您应该使用 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}

当您在 DateValue 类中将 ZonedDateTime 更改为 Date 时,它将打印与您的时区相关的日期。

另见:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 2013-09-18
    • 1970-01-01
    • 2013-05-21
    • 2018-04-20
    相关资源
    最近更新 更多