主要问题是您未能指定时区。
当我在西雅图运行您的代码时,我得到了 2014 年 3 月的 743 小时。为什么?因为我的默认时区。在美国西海岸,Daylight Saving Time 于 2014 年 3 月 9 日星期日 02:00 开始。请参阅此页面,Time change dates in 2014。因此,第 9 天实际上是 23 小时而不是 24 小时。
但如果冰岛有人运行完全相同的代码,她会得到744。为什么?因为冰岛人太聪明了,不会理会夏令时的废话。
此外,作为一个好习惯,您应该在尝试使用天数时调用 Joda-Time 方法withTimeAtStartOfDay()。以前我们使用 Joda-Time 的 midnight 方法,但这些方法已被弃用,因为某些日历中的某些日子 do not have a midnight。
提示:请注意以 standard 命名的 Joda-Time 方法,文档解释说这意味着假设每天 24 小时。换句话说,这些方法忽略了夏令时转换。
这是在 Java 7 中使用 Joda-Time 2.3 的一些示例代码。
// © 2013 Basil Bourque. This source code may be used freely forevery by anyone taking full responsibility for doing so.
// Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 7 and earlier.
// http://www.joda.org/joda-time/
// Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
// JSR 310 was inspired by Joda-Time but is not directly based on it.
// http://jcp.org/en/jsr/detail?id=310
// By default, Joda-Time produces strings in the standard ISO 8601 format.
// https://en.wikipedia.org/wiki/ISO_8601
// Time Zone list: http://joda-time.sourceforge.net/timezones.html
org.joda.time.DateTimeZone seattleTimeZone = org.joda.time.DateTimeZone.forID("America/Los_Angeles");
org.joda.time.DateTimeZone icelandTimeZone = org.joda.time.DateTimeZone.forID("Atlantic/Reykjavik");
// Switch between using 'seattleTimeZone' and 'icelandTimeZone' to see different results (23 vs 24).
org.joda.time.DateTime theNinth = new org.joda.time.DateTime( 2014, 3, 9, 0, 0, seattleTimeZone ) ; // Day when DST begins.
org.joda.time.DateTime theTenth = theNinth.plusDays( 1 ); // Day after DST begins.
// Using "hoursBetween()" method with a pair of DateTimes.
org.joda.time.Hours hoursObject = org.joda.time.Hours.hoursBetween( theNinth.withTimeAtStartOfDay(), theTenth.withTimeAtStartOfDay() );
int hoursInt = hoursObject.getHours();
System.out.println( "Expected 23 from hoursInt, got: " + hoursInt );
// Using an Interval.
org.joda.time.Interval interval = new Interval( theNinth.withTimeAtStartOfDay(), theTenth.withTimeAtStartOfDay() );
System.out.println( "Expected 23 from interval, got: " + org.joda.time.Hours.hoursIn(interval).getHours() );
// Using a Period with Standard days.
org.joda.time.Period period = new org.joda.time.Period( theNinth.withTimeAtStartOfDay(), theTenth.withTimeAtStartOfDay() );
org.joda.time.Hours standardHoursObject = period.toStandardHours();
System.out.println( "Expected 24 from standardHoursObject, got: " + standardHoursObject.getHours() );