用'Z'文字简化解析日期 [英] simpledateformat parsing date with 'Z' literal

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

问题描述

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

  2010-04-05T17:16:00Z 

这是每个 http://www.ietf.org/rfc/rfc3339.txt 。 Z文字暗示UTC
是指定时间的首选参考点。



如果我尝试使用SimpleDateFormat解析它,并且此模式:

  yyyy-MM-dd'T'HH:mm:ss 
/ pre>

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



SimpleDateFormat是无法用这些模式解析字符串:

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

我可以明确地设置TimeZone来使用在SimpleDateFormat上获取预期的输出,但我不认为这是必要的。有没有我失踪的东西?是否有替代日期解析器?

解决方案

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



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



我想你需要一个DatatypeConverter ...

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


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

2010-04-05T17:16:00Z

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

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

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

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

SimpleDateFormat is unable to parse the string with these patterns:

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

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?

解决方案

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.

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

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());
}

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

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