Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Java dates with truncated timezone information

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?

like image 245
PNS Avatar asked Dec 06 '25 02:12

PNS


1 Answers

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

like image 109
Sergey Kalinichenko Avatar answered Dec 08 '25 16:12

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!