Joda解析ISO8601日期在GMT时区 [英] Joda parse ISO8601 date in GMT timezone

查看:327
本文介绍了Joda解析ISO8601日期在GMT时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ISO 8601的日期,可以说: 2012-01-19T19:00-05:00

I have a ISO 8601 date, lets say: 2012-01-19T19:00-05:00

我的机器时区是 GMT + 1

我试图使用joda来解析它并将其转换到相应的GMT日期和时间:

I'm trying to use joda to parse this and convert it to the respective GMT date and time:

DateTimeFormatter simpleDateISOFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mmZZ"); 
creationDate = simpleDateISOFormat.withZone(DateTimeZone.UTC)
                                  .parseDateTime(date + "T" + time)
                                  .toDate(); 

现在我期待的结果是 Fri Jan 20 00:00 :00 CET 2012

相反,我得到: Fri Jan 20 01:00:00 CET 2012

我相信这是因为我在时区 GMT + 1

I believe this is because I'm in timezone GMT + 1.

有没有办法解析伪造成不同时区的日期?

Is there a way to parse the date faking to be in a different time zone?

编辑:基本上问题是当我调用 toDate()方法时。该方法将 DateTime 转换为 Date ,因为我需要做,但我在本地时间转换它。

Basically the problem is when I call the toDate() method. The method converts the DateTime into a Date as I need to do but I transforms it in local time.

有人知道不会施加此限制的转换方法吗?

Do someone know a conversion method which doesn't impose this limitation?

推荐答案

这是一个工作的groovy测试用例。显示可以显示其他时区的次数。

Here's a working groovy testcase. Shows how times in other timezones can be displayed.

import org.joda.time.*
import org.joda.time.format.*

@Grapes([
    @Grab(group='joda-time', module='joda-time', version='1.6.2')
])

class JodaTimeTest extends GroovyTestCase {

    void testTimeZone() {
        DateTimeFormatter parser    = ISODateTimeFormat.dateTimeParser()
        DateTimeFormatter formatter = ISODateTimeFormat.dateTimeNoMillis()

        DateTime dateTimeHere     = parser.parseDateTime("2012-01-19T19:00:00-05:00")

        DateTime dateTimeInLondon = dateTimeHere.withZone(DateTimeZone.forID("Europe/London"))
        DateTime dateTimeInParis  = dateTimeHere.withZone(DateTimeZone.forID("Europe/Paris"))

        assertEquals("2012-01-20T00:00:00Z", formatter.print(dateTimeHere))
        assertEquals("2012-01-20T00:00:00Z", formatter.print(dateTimeInLondon))
        assertEquals("2012-01-20T01:00:00+01:00", formatter.print(dateTimeInParis))
    }
}

注意


  • 您必须调整断言,因为我位于伦敦时区: - )

  • withZone方法会更改DateTime对象的元数据,以指示它的时区。仍然是同一个时间点,只是显示不同的偏移。

这篇关于Joda解析ISO8601日期在GMT时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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