Java的ParseException的同时尝试字符串到日期解析 [英] Java ParseException while attempting String to Date parsing

查看:220
本文介绍了Java的ParseException的同时尝试字符串到日期解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很难解析/格式化日期字符串收到来自Web服务了。我已经尝试多种方法,但没有运气。

I'm having a hard time Parsing/Formatting a Date string received back from a web service. I've attempted multiple approaches, but with no luck.

采样日期字符串:

2011-10-05T03:00:00Z

例外:

W/System.err(10072): java.text.ParseException: Unparseable date: "2011-10-05T05:00:00Z" (at offset 10)
W/System.err(10072):    at java.text.DateFormat.parse(DateFormat.java:626)

样品code:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:SSSS");
Date date = formatter.parse(info.AiringTime);

我发现,如果我删除了T日期和时间之间,并用一个空格代替,这将格式化就好了。任何人有什么建议?

I've found that if I remove the "T" between the date and the time and replace it with a space, it will format just fine. Anybody have any suggestions?

- 更新 -

在寻找更深的API文档,我发现这一点:

After looking deeper into the API documentation, I found this:

所有响应DateTime值是UTC格式。您需要应用的UTC偏移量来计算的本地时间显示。

日期时间是在下列格式之一指定的日期和时间值:

UTC格式:YYYY-MM-DDTHH:MM:SSZ。例如:2011-03-15T02:00:00Z

当地时间的偏移:YYYY-MM-DDTHH:MM:SS +或 - HH:MM(正或负偏移量)。例如,对于美国太平洋时间:2011-03-14T06:00:00 -08:00

在UTC格式的方法有什么建议?

Any suggestions on the UTC format approach?

推荐答案

您可以尝试:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
String dateString = info.AiringTime.replace("Z", "GMT+00:00");
Date date = dateFormat.parse(dateString);

以上code要正确处理这种情况的日期指定一个时区的情况。为:Z再presents的UTC / GMT时区是换成北京时间这样的SimpleDateFormat可以跨$ P $正确PT(我很想知道处理这一点,如果有人知道一个更清洁的方式)。

The above code should correctly handle the case where a timezone is specified in the date. As Z represents the UTC/GMT timezone it is replaced by GMT so the SimpleDateFormat can interpret it correctly (i would love to know a cleaner way of handling this bit if anyone knows one).

这篇关于Java的ParseException的同时尝试字符串到日期解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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