我似乎无法让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));
Here is my Output
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?
SimpleDateFormat
不是线程安全的。如果不注意这一点,可能会遇到严重问题... 在许多情况下,只要您意识到这一事实,它就不会真正产生任何影响。 - desperateCoder