Joda 时间从 dateTime 获取正确的时间

Joda time getting right time from dateTime

我有这个简单的代码:

    DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm yyyy-MM-dd");

    DateTime dateTime = formatter.withZone(DateTimeZone.forID("America/New_York")).parseDateTime("08:30 2015-06-01");
    DateTime dateTime2 = formatter.withZone(DateTimeZone.forID("America/New_York")).parseDateTime("08:30 2015-12-01");

现在是闰日。当我点击 toString 方法时,我得到了这样的东西:

2015-06-01T08:30:00.000-04:00
2015-12-01T08:30:00.000-05:00

这是正确的,我们可以看到 UTC 时间 - 偏移量。但是当我调用 getHourOfDay 时,我得到了 8 而不是预期的 4/3。我究竟做错了什么?请在这里分享一些建议。

嗯,来自 DateTimeFormatter#withZone() 的 Javadoc:

Returns a new formatter that will use the specified zone in preference to the zone of the printed object, or default zone on a parse.

所以,您告诉格式化程序在解析和输出时使用特定的时区,而您给它的输入不包含时区,所以这是预期的结果。本质上你说:

  1. 这是一个没有时区的日期字符串,假设 America/New_York
  2. 解析它
  3. 在时区 America/New_York
  4. 中将日期转换回字符串

这就是它所做的。