Java Date to UTC using gson

2022-09-01 01:17:13

我似乎无法让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"

我显然可以在打电话给Json之前减去1小时,但这似乎是一个黑客。如何配置gson始终转换为UTC?


答案 1

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

感谢链接作者。


答案 2

日期格式中的 Z 采用单引号,必须取消引号才能替换为实际时区。

此外,如果您希望日期采用UTC格式,请先进行转换。