views:

677

answers:

7

I have a weird problem, I need to parse a date string that looks like 1997-02-14T00:00:00.0000000+05:30. The odd thing about the date string is the time zone information. It's +05:30 instead of the usual +0530.

I have the basic format string ready, yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ which would have worked like a charm, if not for the TZ information.

Can anyone suggest a solution to this problem? Is there some kind format string which can handle that kind of TZ info?

Thanks in advance.

+2  A: 

SimpleDateFormat should accept this. From the doc:

For parsing, general time zones are also accepted.

and these are specified as:

GMTOffsetTimeZone:
             GMT Sign Hours : Minutes

which looks like what you have ?

If that fails, then the Joda DateTimeFormat claims to do this. I would be tempted to use Joda regardless, for a whole range of reasons (a more consistent and simpler API, thread-safety for formatters/parsers etc.)

Brian Agnew
I've just tested it, but it doesn't work: new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").parse("Wed, 4 Jul 2001 12:08:56 -07:00")
sfussenegger
What happens if (say) you have GMT-07:00 (I appreciate that's not what you currently have)
Brian Agnew
Yes, it works after prepending GMT to the timezone ("Wed, 4 Jul 2001 12:08:56 GMT-07:00"). But given the format from the question, this (using 'z' instead of 'Z' in format string) still isn't a viable way to parse those dates.
sfussenegger
Yes. Agreed. You may want to check out Joda (for this and other time/date issues)
Brian Agnew
+5  A: 

I've looked into this problem myself several month ago. If I remember correctly, SimpleDateFormat isn't flexible enough to accept other timezone formats (mine was +530). What I did was a simple pre-processing step - i.e. try to remove the colon before passing the String to SimpleDateFormat.

sfussenegger
+2  A: 

Is this by chance a date string that comes from an XML file (ISO8601 format)? Unfortunately there is no (easy) way to parse this with SimpleDateFormat, exactly due to the ':' in the timezone part that SimpleDateFormat has no way to deal with properly.

Have a look at my answer in this other question about how to parse XML datetime strings.

Jesper
+2  A: 

Of course, there is always the hack of preprocessing your String.

If nobody finds a better answer, that would be something already. You could encapsulate it in a method, with a comment to explain the hack.

KLE
+2  A: 

Can you not preprocess with a regex and replace the timezone e.g.

String dateAndTime = ...
String preprocessed = dateAndTime.replace("([+-])(\\d\\d):(\\d\\d)$", "$1$2$3");
// Go on with your life
Dean Povey
A: 

It is still rough around the edges, but should work:

http://pastebin.com/f7bbb0b43

Shantanu Kumar
A: 

I think it should use the replaceAll method of the String for regular expression.

String dateAndTime = ...
String preprocessed = dateAndTime.replaceAll("(GMT)([+-])(\\d\\d):(\\d\\d)", "$2$3$4");
shiami