我似乎无法让gson在Java中将Date转换为UTC时间.... 这是我的代码......
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();
//This is the format I want, which according to the ISO8601 standard - Z specifies UTC - 'Zulu' time
Date now=new Date();
System.out.println(now);
System.out.println(now.getTimezoneOffset());
System.out.println(gson.toJson(now));
这是我的输出
Thu Sep 25 18:21:42 BST 2014 // Time now - in British Summer Time
-60 // As expected : offset is 1hour from UTC
"2014-09-25T18:21:42.026Z" // Uhhhh this is not UTC ??? Its still BST !!
我想要的gson结果和我期待的结果
"2014-09-25T17:21:42.026Z"
我可以清楚地在调用Json之前减去1小时,但这似乎是一个黑客。如何将gson配置为始终转换为UTC?
答案 0 :(得分:89)
经过一些进一步的研究,看来这是一个已知的问题。 gson默认序列化程序始终默认为您的本地时区,并且不允许您指定时区。请参阅以下链接.....
https://code.google.com/p/google-gson/issues/detail?id=281
解决方案是创建一个自定义的gson类型适配器,如链接中所示:
// this class can't be static
public class GsonUTCDateAdapter implements JsonSerializer<Date>,JsonDeserializer<Date> {
private final DateFormat dateFormat;
public GsonUTCDateAdapter() {
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US); //This is the format I need
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); //This is the key line which converts the date to UTC which cannot be accessed with the default serializer
}
@Override public synchronized JsonElement serialize(Date date,Type type,JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(dateFormat.format(date));
}
@Override public synchronized Date deserialize(JsonElement jsonElement,Type type,JsonDeserializationContext jsonDeserializationContext) {
try {
return dateFormat.parse(jsonElement.getAsString());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
}
然后注册如下:
Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new GsonUTCDateAdapter()).create();
Date now=new Date();
System.out.println(gson.toJson(now));
现在可以正确输出UTC中的日期
"2014-09-25T17:21:42.026Z"
感谢链接作者。
答案 1 :(得分:2)
对我来说这个问题的解决方案是创建一个自定义日期适配器(P.S小心,以便导入java.util.Date
而不是java.sql.Date
!)
public class ColonCompatibileDateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer< Date> {
private final DateFormat dateFormat;
public ColonCompatibileDateTypeAdapter() {
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") {
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) {
StringBuffer rfcFormat = super.format(date, toAppendTo, pos);
return rfcFormat.insert(rfcFormat.length() - 2, ":");
}
@Override
public Date parse(String text, ParsePosition pos) {
if (text.length() > 3) {
text = text.substring(0, text.length() - 3) + text.substring(text.length() - 2);
}
return super.parse(text, pos);
}
};
}
@Override public synchronized JsonElement serialize(Date date, Type type,
JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(dateFormat.format(date));
}
@Override public synchronized Date deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) {
try {
return dateFormat.parse(jsonElement.getAsString());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}}
然后在创建GSON对象时使用它
Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new ColonCompatibileDateTypeAdapter()).create();
答案 2 :(得分:1)
日期格式中的Z是单引号,必须不加引号才能被实际时区替换。
此外,如果您希望以UTC格式表示日期,请先转换它。
答案 3 :(得分:1)
我调整了标记solution并对DateFormat
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
public class GsonDateFormatAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
private final DateFormat dateFormat;
public GsonDateFormatAdapter(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
@Override
public synchronized JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(dateFormat.format(date));
}
@Override
public synchronized Date deserialize(JsonElement jsonElement, Type type,JsonDeserializationContext jsonDeserializationContext) {
try {
return dateFormat.parse(jsonElement.getAsString());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
}