DArkO
DArkO

Reputation: 16110

android Date parsing

I have the following string i need to parse to a date:

2012-01-31T08:41:12.5462495+01:00

now i have tried the following code which doesn't work:

public static String FORMAT_DATE_ISO = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";

public static Date fromISODateString(String isoDateString) throws Exception {
    DateFormat f = new SimpleDateFormat(FORMAT_DATE_ISO);
    f.setTimeZone(TimeZone.getTimeZone("Zulu"));
    return f.parse(isoDateString);
}

i am assuming its becase the time zone should be something like +0100 and in my case it is +01:00.

how do i solve this? Thanks.

Upvotes: 0

Views: 3872

Answers (2)

DArkO
DArkO

Reputation: 16110

Thanks to @Jon Skeet for the format string.

i have managed to replace the last colon using

 isoDateString = isoDateString.replaceFirst("(.*):(..)", "$1$2");

so the working code for this will be:

public static String FORMAT_DATE_ISO = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ";

public static Date fromISODateString(String isoDateString) throws Exception {
        isoDateString = isoDateString.replaceFirst("(.*):(..)", "$1$2");
        DateFormat f = new SimpleDateFormat(FORMAT_DATE_ISO);
        f.setTimeZone(TimeZone.getTimeZone("Zulu"));
        return f.parse(isoDateString);
    }

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1501586

There are two problems:

  • The time zone specifier
  • The precision of your seconds

I haven't found an easy way to fix the time zone specifier part in SimpleDateFormat, so I'd be tempted to just manipulate the string - it's a fixed length, so it's not hard to remove the final colon. Then you can use

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

as your format string. Note that according to the docs, Joda Time does handle time zone offsets using colons, so that's another option.

Upvotes: 2

Related Questions