How to save time zone when parsing date?

I am analyzing the date that comes with the time zone information, for example: 1/7/2008 11:00:00 AM -0700 . -0700 corresponds to the current time offset here in California, since we are now in the PDT . If I analyze 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() 

Receive: 2008-01-07T10:00:00.000-08:00 . This is β€œcorrect”, like 10am -0800 = 11 am -0700 , but how can I get the returned date to keep the same time offset (part Z ) that I had at the input?

As a side note, using java.text.SimpleDateFormat , you will get 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, and now we are in the PDT.

+4
source share
1 answer

The date you specified in January that would not be in daylight. Thus, an offset of -0800 is correct if you meant that these times are in Pacific time.

But you did not specify a time zone identifier, such as America/Los_Angeles , so why does JodaTime make this assumption?

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

The main printer / parser can be changed to behave exactly as required using one of the decorator modifiers:

withLocale(Locale) - returns a new formatter that uses the specified language 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 a parsed temporary offset change
withPivotYear() - returns a new formatter with the specified consolidated year
withDefaultYear() - returns a new formatter with the specified year by default

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

The format may contain a locale-specific output, and this will change when the locale formatting changes. Call DateTimeFormatter.withLocale (Locale) to switch the language.

Since you do not want to use a specific language or time zone, I believe that 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 documents for .withOffsetParsed() behavior, which is what you are asking for.

+4
source

Source: https://habr.com/ru/post/1479832/


All Articles