javac#androidasp.net-web-apiasp.net-web-api2

gson JsonSyntaxException to Java Date from .net DateTime


How can I convert C#'s DateTime format from gson to Java Date? In gson which setDateFormat is correct? C#

DateTime time = DateTime.Now;

JSON

{
  "date_time": "2015-04-24T09:22:08.6964069+08:00"
}

Android

private Date date_time;

Gson gson=  new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();
gson.fromJson(resultString, objectClass);

E/AndroidRuntime(24671): Caused by: com.google.gson.JsonSyntaxException: 2015-04-24T16:20:08.3672729+08:00
E/AndroidRuntime(24671): Caused by: java.text.ParseException: Unparseable date: "2015-04-24T16:20:08.3672729+08:00"
E/AndroidRuntime(24671): at java.text.DateFormat.parse(DateFormat.java:626)
E/AndroidRuntime(24671): at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:79)

Solution

  • If you can't work with the X pattern symbol wich is typically used for the ISO 8601 time zone you cannot take care of this date format, because of the colon in the time zone. If you can make use of it, the pattern would look like this:

    yyyy-MM-dd'T'HH:mm:ss.SSSSSSSXXX
    

    A workaround would be to handle it as a String, remove the colon from it (e.g. replaceAll(String) and afterwards format it with the RFC 822 time zone (pattern symbol Z):

    String time = inputTime.replaceAll("([\\+\\-]\\d\\d):(\\d\\d)","$1$2"));
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZZZ");
    Date myDate = format.parse(time);
    

    Note: Because of the combination of milliseconds and time zone, you have to hardset the digitamount.

    The SimpleDateFormat provides the underlying conventions, as stated in the GsonDoc.