Search code examples
androidretrofit2

Failed to parse date ["2022-02-21 13:26:59.213+00:00"]: Invalid time zone indicator ' ' - Using Retrofit and SimpleDateFormat


I am consuming a C# webapi from an Android app using Retrofit. I have been getting an error:

Failed to parse date ["2022-02-21 12:10:18.043+00:00"]: Invalid time zone indicator ' '

The format I am using to return a date value from the C# dotnet api is:

"yyyy-MM-dd HH:mm:ss.fffzzz"

I found the formatting options on this page.

The format I am using to consume on the Android side is:

"yyyy-MM-dd'T'HH:mm:ss.SSSZ"

And the Gson options are based on SimpleDateFormat.

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

I Also tried with this:

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

Because of this on the SimpleDateFormat page: enter image description here

But got the same error:

Caused by: java.text.ParseException: Failed to parse date ["2022-02-21 13:52:38.207+00:00"]: Invalid time zone indicator ' '

Has anybody run into this before?

I read this post and there were a lot of responses explaining Z, but and a reference to ISO 8601, which covers the offsets: enter image description here

It even refers to the 0 offset: https://en.wikipedia.org/wiki/ISO_8601


Solution

  • According to your given date: 2022-02-21 12:10:18.043+00:00 your date format should look like yyyy-MM-dd HH:mm:ss.SSSZ.

    Source: http://tutorials.jenkov.com/java-internationalization/simpledateformat.html

    patterns

    Sample code:

    void parseDateExample() {
            String dateToParse = "2022-02-21 12:10:18.043+00:00";
    
            String dateFormat = "yyyy-MM-dd HH:mm:ss.SSSZ";
    
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.getDefault());
    
            try {
                Date date = sdf.parse(dateToParse);
                Log.d("Mg-date", date.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
    
    
        }