Question

I parse a date that comes with time zone information, say: 1/7/2008 11:00:00 AM -0700. The -0700 corresponds to the current time offset here in California, since we are now in PDT. If I parse it and show it with:

org.joda.time.format.DateTimeFormat.forPattern("M/d/yyyy hh:mm:ss a Z")
    .parseDateTime("1/7/2008 11:00:00 AM -0700").toString()

I get: 2008-01-07T10:00:00.000-08:00. This is "correct", as 10am -0800 = 11 am -0700, but how can I get the returned date to keep the same time offset (the Z part) I had in the input?

As a side note, using java.text.SimpleDateFormat give a similar result: new SimpleDateFormat("M/d/yyyy hh:mm:ss a Z").parse("1/7/2008 11:00:00 AM -0700").toString() returns Mon Jan 07 10:00:00 PST 2008, and PST = -0800, while we are now in PDT.

Was it helpful?

Solution

The date you provided is in January, which would not have been on daylight time. So the -0800 offset is correct if you meant these times to be in Pacific time.

But you didn't specify a time zone ID like America/Los_Angeles, so why is JodaTime making this assumption?

The answer can be found in the documentation for the DateTimeFormatter class:

The underlying printer/parser can be altered to behave exactly as required by using one of the decorator modifiers:

withLocale(Locale) - returns a new formatter that uses the specified locale
withZone(DateTimeZone) - returns a new formatter that uses the specified time zone
withChronology(Chronology) - returns a new formatter that uses the specified chronology
withOffsetParsed() - returns a new formatter that returns the parsed time zone offset
withPivotYear() - returns a new formatter with the specified pivot year
withDefaultYear() - returns a new formatter with the specified default year

The documentation for the DateTimeFormatter.forPattern() method says:

The format may contain locale specific output, and this will change as you change the locale of the formatter. Call DateTimeFormatter.withLocale(Locale) to switch the locale.

Since you don't want to use a specific locale or time zone, I believe you should use the following:

org.joda.time.format.DateTimeFormat.forPattern("M/d/yyyy hh:mm:ss a Z")
        .withOffsetParsed()
        .parseDateTime("1/7/2008 11:00:00 AM -0700").toString()

See these docs for the behavior of .withOffsetParsed(), which is exactly what you are asking about.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top