Java日期到UTC使用gson [英] Java Date to UTC using gson
问题描述
我似乎无法让gson将日期转换为UTC时间。
这是我的代码...
I can't seem to get gson to convert a Date to UTC time in java.... Here is my code...
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结果
The gson result I want and what I was expecting
"2014-09-25T17:21:42.026Z"
我可以清楚地减去1小时前的电话,但这似乎是一个黑客。如何将gson配置为始终转换为UTC?
I can clearly just subtract 1hr before the call toJson but this seems to be a hack. How can I configure gson to always convert to UTC ?
推荐答案
经过进一步研究,似乎这是一个已知的问题。 gson默认序列化程序始终默认为您的本地时区,不允许您指定时区。请参阅以下链接.....
After some further research, it appears this is a known issue. The gson default serializer always defaults to your local timezone, and doesn't allow you to specify the timezone. See the following link.....
https://code.google.com/p/google-gson/issues/detail?id=281
解决方案是创建一个自定义gson类型的适配器,如链接中所示:
The solution is to create a custom gson type adaptor as demonstrated in the link:
// 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中的日期
This now correctly outputs the Date in UTC
"2014-09-25T17:21:42.026Z"
谢谢你的链接作者。
这篇关于Java日期到UTC使用gson的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!