使用截断的时区信息解析Java日期 [英] Parsing Java dates with truncated timezone information

查看:142
本文介绍了使用截断的时区信息解析Java日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下日期字符串




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



这是在Java中使用以下 SimpleDateFormat 模式:




  • yyyy-MM-dd HH:mm:ss.SSSZ / li>


但是,如果上述时区信息被截断为2位数,就像




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



日期字符串不符合任何有效的格式,所以没有可以使用的 SimpleDateFormat 模式,以正确地解析它。 / p>

有没有任何解决方法解决截断的时区正确没有字符串预处理



如果不是,哪一个正则表达式对于在一轮中这样的日期字符串 进行预处理是最佳的,例如使用 replaceFirst()调用,如这个类似问题

解决方案

我不知道一个没有字符串的好解决方案预处理,但如果 replaceFirst 可以接受,您可以使用此代码段:

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

此代码将两个零追加到以< plus | minus>< digit>< digit> 链接到ideone )。


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?

解决方案

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

这篇关于使用截断的时区信息解析Java日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆