Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joda parse ISO8601 date in GMT timezone

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

Now the result that I'm expecting is Fri Jan 20 00:00:00 CET 2012

Instead I'm getting: Fri Jan 20 01:00:00 CET 2012

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?

Edit: 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?

like image 351
Sergio Arrighi Avatar asked Jan 31 '12 09:01

Sergio Arrighi


1 Answers

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.
like image 84
Mark O'Connor Avatar answered Sep 28 '22 14:09

Mark O'Connor