Parsing a date string using java.text.SimpleDateFormat

梦想与她 提交于 2019-12-04 06:10:03

问题


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.


回答1:


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 



回答2:


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.




回答3:


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.




回答4:


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.




回答5:


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




回答6:


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

http://pastebin.com/f7bbb0b43




回答7:


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


来源:https://stackoverflow.com/questions/1554852/parsing-a-date-string-using-java-text-simpledateformat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!