模糊的问题
您没有提供实际值,因此我们无法准确确定问题所在。我们不知道today 和dueDate 变量是什么。
过时
这个问题现在已经过时了,因为包括 java.util.Date/.Calendar 在内的麻烦的旧日期时间类已被新的java.time 框架取代。见Tutorial。由JSR 310 定义,受Joda-Time 启发,并由ThreeTen-Extra 项目扩展。
在 java.time 中:
-
Instant 是 UTC 时间线上的时刻。
-
ZoneId 表示时区。使用正确的时区名称,不要使用“EST”或“IST”之类的 3-4 个字母代码,因为它们既不标准化也不唯一。
- 从概念上讲,
ZonedDateTime = Instant + ZoneId。
三十加分
不幸的是,java.time 不包括计算日期时间值之间经过的天数的工具。我们可以使用ThreeTen-Extra 项目及其Days 类和between 方法来提供该计算。 ThreeTen-Extra 项目是一组在 JSR 过程中被认为对 java.time 不重要的特性。
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now ( zoneId );
ZonedDateTime then = now.minusDays ( 4 );
ZonedDateTime due = now.plusDays ( 3 );
Integer days = org.threeten.extra.Days.between ( then , due ).getAmount ();
转储到控制台。
System.out.println ( "From then: " + then + " to due: " + due + " = days: " + days );
从那时起:2015-10-31T16:01:13.082-04:00[美国/蒙特利尔] 截止日期:2015-11-07T16:01:13.082-05:00[美国/蒙特利尔] = 天数:7
乔达时间
对于 Android 或更早版本的 Java,请使用出色的 Joda-Time 库。
Days 类很聪明,可以处理 Daylight Saving Time (DST) 等异常情况。
请注意,与 java.util.Date 不同,Joda-Time DateTime 对象知道自己的时区。
// Specify a time zone rather than rely on default.
DateTimeZone timeZone = DateTimeZone.forID( "America/Regina" ); // Or "Europe/London".
DateTime now = new DateTime( timeZone );
DateTime startOfToday = now.withTimeAtStartOfDay();
DateTime fewDaysFromNow = now.plusDays( 3 );
DateTime startOfAnotherDay = fewDaysFromNow.withTimeAtStartOfDay();
Days days = Days.daysBetween( startOfToday, startOfAnotherDay );
转储到控制台...
System.out.println( days.getDays() + " days between " + startOfToday + " and " + startOfAnotherDay + "." );
运行时……
3 days between 2014-01-21T00:00:00.000-06:00 and 2014-01-24T00:00:00.000-06:00.