Java ISO 8601 毫秒和改造
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32285611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ISO 8601 with milliseconds and Retrofit
提问by Javier Manzano
I cannot set properly the date format when using retrofit and trying to read a date like this:
使用改造并尝试读取这样的日期时,我无法正确设置日期格式:
2015-08-29T11:22:09.815479Z
An the GSONconverter I'm setting is like this:
我正在设置的GSON转换器是这样的:
GsonConverter gsonConverter = new GsonConverter(
new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSz")
.create()
);
Any clues on what's the problem?
有关问题出在哪里的任何线索?
回答by grim
Java Datehas millisecond precision so I've been creating the Gson
object like so:
Java Date具有毫秒精度,所以我一直在Gson
像这样创建对象:
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
.create();
Of course, in a case like this, the microseconds are being truncated whether you put SSS
or SSSSSS
. It is also assumed that the last character of the converted string is always a Z
.
当然,在这种情况下,无论是 putSSS
还是SSSSSS
. 还假设转换后的字符串的最后一个字符总是 a Z
。
To explain why your pattern didn't work, you used z
(lowercase z) which according to the documentation represents a General Timezone(e.g., Pacific Standard Time; PST; GMT-08:00
). Additionally, if you were to use Z
(uppercase Z), it would also not work since it represents an RFC 822 time zone(e.g., -0800
).
为了解释为什么您的模式不起作用,您使用了z
(lowercase z) 根据文档表示通用时区(例如,Pacific Standard Time; PST; GMT-08:00
)。此外,如果您要使用Z
(大写 Z),它也将不起作用,因为它代表RFC 822 时区(例如,-0800
)。
In another scenario where instead of the Z
you have a time zone offset (e.g., -08
, -0800
, or -08:00
), you can use X
, XX
, or XXX
to represent an ISO 8610 time zone. But that requires Java 7 or 8 (I don't think Android is compatible with Java 8 at the moment).
在另一种情况下,您可以使用、、 或来表示ISO 8610 时区,而不是Z
具有时区偏移量(例如-08
、-0800
、 或-08:00
)。但这需要 Java 7 或 8(我认为 Android 目前与 Java 8 不兼容)。X
XX
XXX
Another method would be to write your own Gson
Serializer and Deserializer; although I haven't tried.
另一种方法是编写自己的Gson
Serializer 和 Deserializer;虽然我没试过。
It's also worth looking at java.sql.Timestampclass which is also supported by Gson
and has more fine grained precision (nanoseconds) but it's also an option I haven't explored.
还值得一看java.sql.Timestamp类,它也受支持Gson
并具有更细粒度的精度(纳秒),但它也是我尚未探索的选项。