使用 gson 将 Java 日期转换为 UTC

标签 java json date gson utc

我似乎无法让 gson 在 java 中将日期转换为 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"

我可以清楚地在调用 toJson 之前减去 1 小时,但这似乎是一个 hack。如何将 gson 配置为始终转换为 UTC?

最佳答案

经过进一步研究,这似乎是一个已知问题。 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"

感谢链接作者。

关于使用 gson 将 Java 日期转换为 UTC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26044881/

相关文章:

java - 数组操作 : HackerRank Questions : JAVA

jquery - 如何打印 json 对象数组

ios - 向下滚动时出现 fatal error

json - 如何处理SQL中的错误并控制存储过程

javascript - 如何将 dd/mm/yyyy 字符串转换为 JavaScript Date 对象?

python - 根据日期条件删除行

java - JComboBox 的问题

java - 如何运行Java程序

java - 测试 DDS 阅读器接收消息以进行 Java 单元测试

javascript - 修改函数以计算到新的一年而不返回值 12/33/2014