Parsing Java dates with truncated timezone informa

2019-07-02 00:12发布

问题:

Consider the following date string

  • 2012-10-01 01:02:03.004+0500

This is recognized in Java using the following SimpleDateFormat pattern:

  • yyyy-MM-dd HH:mm:ss.SSSZ

If, however, the timezone information above is truncated to 2 digits, i.e. like

  • 2012-10-01 01:02:03.004+05

the date string does not comply to any valid format, so there is no SimpleDateFormat pattern that could be used in order to correctly parse it.

Is there any workaround for parsing the truncated timezone correctly without string preprocessing?

If not, which regular expression would be optimal for that preprocessing to be done for a large number of such date strings in 1 round, e.g. using a replaceFirst() call, as in this similar question?

回答1:

I do not know a good solution without string preprocessing, but if replaceFirst is acceptable, you can use this code snippet:

dateStr.replaceFirst("(?<=[+-]\\d\\d)$", "00")

This code appends two zeros to strings ending in <plus|minus><digit><digit> (link to ideone).