ISO 8601 with milliseconds and retrofit

I canโ€™t set the date format correctly when using the modification and try to read a date like this:

2015-08-29T11:22:09.815479Z 

The GSON converter that I install looks like this:

 GsonConverter gsonConverter = new GsonConverter( new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSz") .create() ); 

Any clues about what the problem is?

+8
source share
2 answers

Java Date has precision in milliseconds, so I have a Gson object as follows:

 Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .create(); 

Of course, in this case, microseconds are truncated, regardless of whether you set SSS or SSSSSS . It is also assumed that the last character of the converted string is always Z

To explain why your pattern doesn't work, you used z (lowercase z), which, according to the documentation, represents the common Pacific Standard Time; PST; GMT-08:00 Pacific Standard Time; PST; GMT-08:00 Pacific Standard Time; PST; GMT-08:00 belt (e.g. Pacific Standard Time; PST; GMT-08:00 ). Also, if you were to use Z (uppercase Z), this would not work either, since it represents the time zone of RFC 822 (e.g. -0800 ).

In another scenario, where instead of Z you have a time zone offset (for example, -08 , -0800 or -08:00 ), you can use X , XX or XXX to represent the ISO 8610 time zone . But this requires Java 7 or 8 (at the moment I do not think that Android is compatible with Java 8).


Another way would be to write your own Gson Serializer and Deserializer ; although I have not tried

It's also worth Gson look at the java.sql.Timestamp class , which is also supported by Gson and has finer precision (nanoseconds), but I have not explored this option yet.

+6
source

You can use the Java 8 Instant class to easily analyze ISO-8601 timestamps without explicitly setting the format string, for example:

 String input = "2018-11-07T00:25:00.073876Z"; Instant instant = Instant.parse(input); 
0
source

All Articles