Fractional Number of Days between DateTime objects in Java
如何查找两个Joda Time日期时间实例之间的天数分数差异?
days.daysBetween(start,end).getdays()给我一个类似10/15等的整数。我需要得到的是精确的值,如10.15或15.78。
如果您使用hours.hoursbetween,可能会因四舍五入而错过分钟。
试试这个:(end.getmillis-start.getmillis())/(1000*3600*24)
要获得带分数的天数,请根据精度要求以足够小的单位计算差异,然后在进行转换为天数的除法之前转换为
1 2 3 4 5 6 7 | DateTimeZone zone = DateTimeZone.forID("Europe/Copenhagen"); DateTime date1 = new DateTime(1997, 1, 1, 0, 0, zone); DateTime date2 = new DateTime(1997, 3, 29, 12, 0, zone); int seconds = Seconds.secondsBetween(date1, date2).getSeconds(); double days = (double) seconds / (double) TimeUnit.DAYS.toSeconds(1); System.out.println("Difference in days is" + days); |
此代码段输出:
Difference in days is 87.5
我们需要提供正确的时区,以考虑夏季(DST)之间的转换。在我的例子中,这两天都是欧盟一年中标准时间的一部分,因此12小时转换为0.5天。如果我选择了4月初的一个日期,在夏季开始之后,这不会是事实。例如:
1 | DateTime date2 = new DateTime(1997, 4, 1, 12, 0, zone); |
Difference in days is 90.45833333333333
由于
这个答案是在这个重复的问题出现的时候写的,并且示例日期时间是从那里开始的。
感谢来自评论的输入,我让它精确到秒,使用:
1 | double days = Seconds.secondsBetween(start, end).getSeconds()/86400; |
减去以毫秒为单位的时间,然后除以每天的毫秒数:
1 | double diff = (end.getMillis() - start.getMillis()) / 86400000d; |
试验
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | DateTime start = new DateTime(2015, 1, 1, 0, 0, 0, 0); // Jan 1, 2015 DateTime end = new DateTime(2015, 7, 4, 14, 23, 55, 876); // Jul 4, 2015 at 2:23:55.876 PM final int MILLIS_PER_DAY = 24 * 60 * 60 * 1000; // 86_400_000 double diff = (double)(end.getMillis() - start.getMillis()) / MILLIS_PER_DAY; System.out.println(diff); int days = (int)diff; diff = (diff - days) * 24; int hours = (int)diff; diff = (diff - hours) * 60; int minutes = (int)diff; diff = (diff - minutes) * 60; int seconds = (int)diff; diff = (diff - seconds) * 1000; int millis = (int)Math.round(diff); System.out.println(days +" days," + hours +" hours," + minutes +" minutes," + seconds +" seconds," + millis +" millis"); |
产量
1 2 | 184.55828560185185 184 days, 13 hours, 23 minutes, 55 seconds, 876 millis |
请注意,由于夏令时的缘故,现在只有13个小时,而不是14个小时。