代码之家  ›  专栏  ›  技术社区  ›  Steve McLeod

我怎样才能用joda time解析一个日期,包括时区

  •  53
  • Steve McLeod  · 技术社区  · 16 年前

    这段代码总是将日期解析为当前时区,而不是解析字符串中的时区。

    final DateTimeFormatter df = DateTimeFormat
            .forPattern("EEE MMM dd HH:mm:ss 'GMT'Z yyyy");
    final DateTime dateTime = df
            .parseDateTime("Mon Aug 24 12:36:46 GMT+1000 2009");
    System.out.println("dateTime = " + dateTime);
    // outputs dateTime = 2009-08-24T04:36:46.000+02:00
    

    它输出:

    dateTime = 2009-08-24T04:36:46.000+02:00
    

    然而,我期望:

    dateTime = 2009-08-24T04:36:46.000+10:00
    

    知道我做错了什么吗?

    2 回复  |  直到 11 年前
        1
  •  75
  •   Björn Pollex    13 年前

    好的,进一步的谷歌搜索给了我我自己的问题的答案:使用 withOffsetParsed() 如此:

    final DateTimeFormatter df = DateTimeFormat
            .forPattern("EEE MMM dd HH:mm:ss 'GMT'Z yyyy");
    final DateTime dateTime = df.withOffsetParsed()
            .parseDateTime("Mon Aug 24 12:36:46 GMT+1000 2009");
    

    这是可行的。

        2
  •  35
  •   z0mb1ek    13 年前

    您还可以选择:

    // parse using the Paris zone
    DateTime date = formatter.withZone(DateTimeZone.forID("Europe/Paris")).parseDateTime(str);