开发者

Parsing a date string using java.text.SimpleDateFormat

I have a weird problem, I need to parse a date string that looks like 1997-02-14T00:00:00.000000开发者_开发技巧0+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.


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.


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 


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.


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.


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.)


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

http://pastebin.com/f7bbb0b43


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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜