开发者

Joda Time and timezone offsets

开发者 https://www.devze.com 2023-03-26 03:18 出处:网络
I have a problem with timezone offsets in Joda Time. I think it is simply a problem uf understanding.

I have a problem with timezone offsets in Joda Time. I think it is simply a problem uf understanding.

I have the following parser and printer:

// The formatter for the timezone
    DateTimeFormatter timezoneFormatter = new DateTimeFormatterBuilder().appendTimeZoneOffset(null, true, 2, 2)
                .toFormatter();

    // This formatter equals: yyyy-MM-dd
    DateTimeFormatter dhmsFormatter = ISODateTimeFormat.date();

    // Here a parser is created that parses a string of the form yyyy-MM-dd. Further the string may have
    // a timezone. withOffsetParsed makes the parser to respect the set timezone (if one is set)
    DATE_TIME_PARSER = new DateTimeFormatterBuilder().append(dhmsFormatter)
                .appendOptional(timezoneFormatter.getParser()).toFormatter().withOffsetParsed();

    // Here a printer is created that prints this dateTime in the form yyyy-MM-dd ZZ
    DATE_TIME_PRINTER = new DateTimeFormatterBuilder().append(dhmsFormatter).append(timezoneFormatter.getPrinter()).toFormatter();

This wor开发者_运维知识库ks as expected when I parse and print dates that have an offset set. E.g.:

  • 2006-11-11-09:00
  • 2004-12-01+00:00

Those two values are parsed and printed as they are written above here.

Now my question: I want to be able to set a default time zone (i.e. default offset when none is set). I'll do that like this: DateTimeZone.setDefault(DateTimeZone.forID("Etc/GMT+1"));

My expectation is now that 2006-11-11 is parsed and printed as 2006-11-11+01:00, but in fact it prints 2006-11-11-01:00.

I think this is somehow correct because here http://www.joda.org/joda-time/timezones.html it is written that Etc/GMT+1 has the standard offset of -01:00. So what's wrong? I want to offset to reflect the GMT-offset. I also think that my values above are wrong: means 2006-11-11-09:00 is not the timezone of "Japan" but it is the timezone of "US/Alaska".

I hope my problem is clear. Does anybody have an answer for my not-understanding :)?

Best regards, Florian


Can it be that you instantiate DateTimeFormatter or a DateTime before setting a default timezone?

Anyway, I believe withZone() method should give you the formatter/parser you're looking for.

0

精彩评论

暂无评论...
验证码 换一张
取 消