java - 正确的日期格式用于 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();
请让我知道使用哪种格式。
解决方案
这种格式可以由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
为上课时Date
,DateValue
它将打印与您的时区相关的日期。
也可以看看:
推荐阅读
- reactjs - 无法通过单击按钮将我的文本保持在状态
- json - 如何使用控制台在 aws SNS 中发送 json 消息正文
- ios - 缩放后 UiImageView 模糊
- javascript - 如何重命名对象数组中对象的所有键?
- c++ - 如何在循环内的c ++中使用空格输入
- javascript - 从不同的对象数组中查找键值的计数
- kubernetes - 带有一个数据库的 Spring Batch 和多实例 Kubernets 应用程序
- c# - 为什么我们要使用各种变量类型,如 int、char、string 等,而不仅仅是 c# 中的 var?
- reactjs - 期望一个赋值或函数调用,而是看到一个表达式 @typescript-eslint/no-unused-expressions (React)
- javascript - 可以将剪贴板文本/html mimetype 复制到 javascript 中的 text/plain 吗?