本文介绍了SimpleDateFormat 用 'Z' 文字解析日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析如下所示的日期:

I am trying to parse a date that looks like this:

2010-04-05T17:16:00Z

这是 http://www.ietf.org/rfc/rfc3339 的有效日期.txt.'Z' 字面量(引号)暗示 UTC 是指定时间的首选参考点."

This is a valid date per http://www.ietf.org/rfc/rfc3339.txt. The 'Z' literal (quote) "imply that UTC is the preferred reference point for the specified time."

如果我尝试使用 SimpleDateFormat 和这种模式来解析它:

If I try to parse it using SimpleDateFormat and this pattern:

yyyy-MM-dd'T'HH:mm:ss

它将被解析为 Mon Apr 05 17:16:00 EDT 2010

it will be parsed as a Mon Apr 05 17:16:00 EDT 2010


SimpleDateFormat 无法解析具有这些模式的字符串:


SimpleDateFormat is unable to parse the string with these patterns:

yyyy-MM-dd'T'HH:mm:ssz
yyyy-MM-dd'T'HH:mm:ssZ

我可以明确设置 TimeZone 以在 SimpleDateFormat 上使用以获得预期的输出,但我认为这没有必要.有什么我想念的吗?是否有替代日期解析器?

I can explicitly set the TimeZone to use on the SimpleDateFormat to get the expected output, but I don't think that should be necessary. Is there something I am missing? Is there an alternative date parser?

推荐答案

在模式中,包含'z'日期时间组件表示时区格式需要符合一般时区 "标准",例如太平洋标准时间;太平洋标准时间;GMT-08:00.

In the pattern, the inclusion of a 'z' date-time component indicates that timezone format needs to conform to the General time zone "standard", examples of which are Pacific Standard Time; PST; GMT-08:00.

Z"表示时区符合 RFC 822 时区 标准,例如-0800.

A 'Z' indicates that the timezone conforms to the RFC 822 time zone standard, e.g. -0800.

我认为你需要一个 DatatypeConverter ...

I think you need a DatatypeConverter ...

@Test
public void testTimezoneIsGreenwichMeanTime() throws ParseException {
    final Calendar calendar = javax.xml.bind.DatatypeConverter.parseDateTime("2010-04-05T17:16:00Z");
    TestCase.assertEquals("gotten timezone", "GMT+00:00", calendar.getTimeZone().getID());
}

这篇关于SimpleDateFormat 用 'Z' 文字解析日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-17 16:48