Joda parse ISO8601 date in GMT timezone

前端 未结 3 1009
走了就别回头了
走了就别回头了 2021-02-19 02:30

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

My machine timezone is GMT+1

I\'m trying to use joda to parse this and convert

3条回答
  •  醉梦人生
    2021-02-19 03:30

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

    Note:

    • You'll have to adjust the assertions, because I'm located in the London timezone :-)
    • The "withZone" method changes the DateTime object's metadata to indicate it's timezone. Still the same point in time, just displayed with a different offset.

提交回复
热议问题