我有这种格式的日期字符串:
2011/02/14 00:00:00.000 -0800
我通过以下方式将其转换为java Date对象:
this.pubDate = Date.parse("yyyy/MM/dd 00:00:00.000 Z", obj.SourcePublishedDate);
上述结果产生结果2011/02/14 00:00:00.000 +0000 我有两个关于结果的问题。解析0时,我使用格式“yyyy / MM / dd 00:00:00.000 Z”。有没有更好的方法来维持0?第二个问题是关于时区,由于某种原因我得到的是+0000而不是-0800。怎么能解析正确的价值? 很感谢你的时间。
答案 0 :(得分:2)
如果您使用Java 8+。您可以使用OffsetDateTime来存储日期/时间和时间。时区
// Parser
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss.SSS Z");
// Parse date/time with time zone
// OffsetDateTime odtWithTime = OffsetDateTime.parse("2011/02/14 00:00:00.000 -0800", formatter);
OffsetDateTime odtWithTime = OffsetDateTime.parse("2011/02/14 09:30:00.999 -0800", formatter);
// odtWithTime: 2011-02-14T09:30:00.999-08:00
// Remove time from odtWithTime
LocalDateTime ldtWithoutTime = odtWithTime.toLocalDate().atStartOfDay();
OffsetDateTime odtWihtoutTime = OffsetDateTime.of(ldtWithoutTime, odtWithTime.getOffset());
// odtWihtoutTime: 2011-02-14T00:00-08:00
// All time information are reset to Zero
摘要:您解析日期/时间&然后将时区重置为零。
答案 1 :(得分:1)
0
作为文字您尝试将2011/02/14 00:00:00.000 -0800
之类的字符串解析为日期时间是Catch‑22。
首先,您不能使用yyyy/MM/dd 00:00:00.000 Z
的解析模式,因为零没有解析模式代码。角色0
没有任何意义作为代码。
其次,您可能会考虑在时间部分添加单引号标记,如下所示:yyyy/MM/dd '00:00:00.000' Z
,以告诉格式化程序期望全球零时间值的字符串文字。虽然可以告诉格式化程序期望这样的字符串,但问题是字符串文字在语义上被忽略。所以现在你没有输入时间价值。使用日期但没有时间无法完成日期时间的解析。抛出异常。
解决方案是改变你的心态。意识到你可以在任何时间接收输入,不一定是全球零。
请注意:即使您确定您将始终获得当天第一时刻的输入,但这并不总是意味着全部为零!在某些时区,由于Daylight Saving Time (DST)或其他异常情况,当天的第一时刻不总是00:00:00.000
。
因此,只需告诉格式化程序将零解析为任何有效的时间。请注意下面示例代码中解析模式中使用的HH:mm:ss.SSS
。
我不知道您在问题中提到的Date
课程。
无论如何,您应该使用Java 8及更高版本中内置的java.time框架。见Tutorial。这些类取代了旧的麻烦的日期时间类,如java.util.Date/.Calendar。
特别是你需要java.time.OffsetDateTime
类,因为它代表时间轴上具有特定offset-from-UTC的时刻。如果您有一个完整的时区而不仅仅是一个偏移量,那么您将使用ZonedDateTime
。
为了好玩,示例代码还在Instant
的时间轴上使用UTC。从概念上讲,Instant
是OffsetDateTime
和ZonedDateTime
的基础。
重要说明:java.time中的解析代码与旧的java.text.SimpleDateFormat代码类似,但不完全相同。请务必阅读DateTimeFormatter
的文档。
String input = "2011/02/14 00:00:00.000 -0800";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "yyyy/MM/dd HH:mm:ss.SSS X" );
OffsetDateTime odt = OffsetDateTime.parse ( input , formatter );
转储到控制台。
System.out.println ( "input: " + input + " | odt: " + odt + " | instant: " + odt.toInstant () );
输入:2011/02/14 00:00:00.000 -0800 | odt:2011-02-14T00:00-08:00 |时间:2011-02-14T08:00:00Z
作为输出生成的字符串默认为标准ISO 8601格式。如果您需要其他格式,请定义并传递另一个DateTimeFormatter
。