【发布时间】:2014-12-30 15:13:47
【问题描述】:
日期格式 1418805300000-0100 应该使用什么模式? (时间戳和时区)
GsonBuilder().setDateFormat("?????????????-Z")
解决方案:
-
使用适配器创建新的 GSON
private static Gson createGson(){ return new GsonBuilder().disableHtmlEscaping() .registerTypeHierarchyAdapter(Date.class, new DateTimeSerializer()) .registerTypeHierarchyAdapter(Date.class, new DateTimeDeserializer()) .create(); } public static MyClass fromJson(String json) { return createGson().fromJson(json, MyClass.class); } public String toJson() { return createGson().toJson(this); } -
JSON 序列化器
private static class DateTimeSerializer implements JsonSerializer<Date> { @Override public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { // hodgie code return new JsonPrimitive(src.getTime() + new SimpleDateFormat("Z").format(src)); } } -
反序列化器
private static class DateTimeDeserializer implements JsonDeserializer<Date> { @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // hodgie code return new Date(Long.valueOf((json).getAsString().substring(0, 13))); } }
【问题讨论】:
-
那些毫秒是多少?如果它们是时间戳,为什么需要时区?
-
是的,这是时间戳,我会纠正我的问题。带有时区的时间戳——这是来自服务器的响应。我不能修改它。
-
(如果是时间戳,则不需要时区。)
-
您可以看到 oracle 站点:docs.oracle.com/cd/B19306_01/server.102/b14225/… "TIMESTAMP WITH TIME ZONE 是 TIMESTAMP 的变体,其值中包含时区偏移量或时区区域名称。"