2

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

lcj
  • 1,355
  • 16
  • 37
  • Try without the +00:00 – blackapps Feb 21 '22 at 14:07
  • But isn't it a valid format? I would like one which woks for all dates and offsets. – lcj Feb 21 '22 at 15:07
  • `java.time.OffsetDateTime.parse( "2022-02-21 12:10:18.043+00:00".replace( " " , "T" ) )`. The `SimpleDateFormat`, `Date`, and `Calendar` classes were supplanted years ago by the modern *java.time* classes built into Java 8 and later as well as Android 26+. For earlier Android, access most of the *java.time* functionality via the latest tooling with "API desugaring". – Basil Bourque Feb 22 '22 at 02:22

1 Answers1

1

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();
        }


    }
Mayur Gajra
  • 8,285
  • 6
  • 25
  • 41
  • Caused by: java.text.ParseException: Failed to parse date ["2022-02-21 11:18:29.153-05:00"]: Invalid time zone indicator ' ' with this format "yyyy-MM-dd'T'HH:mm:ss.SSSZ" – lcj Feb 21 '22 at 16:20
  • "yyyy-MM-dd HH:mm:ss.SSSZ" worked. – lcj Feb 21 '22 at 16:24