Java中DateTime对象之间的小数天数

如何找到两个Joda-Time DateTime实例之间天数的小数差异?

Days.daysBetween(开始,结束).getDays()给我一个像10/15等的整数。我需要得到的是像10.15或15.78的精确值


如果您使用Hours.hoursBetween,则可能会由于四舍五入而错过分钟。

试试这个:(end.getMillis - start.getMillis())/(1000 * 3600 * 24)


以毫秒为单位减去时间并按每天毫秒数除数:

double diff = (end.getMillis() - start.getMillis()) / 86400000d;

测试

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");

产量

184.55828560185185
184 days, 13 hours, 23 minutes, 55 seconds, 876 millis

请注意,由于夏令时只有13个小时,而不是14个小时。


感谢来自评论的输入,我使用下面的代码精确地处理秒数:

double days = Seconds.secondsBetween(start, end).getSeconds()/86400;
链接地址: http://www.djcxy.com/p/6247.html

上一篇: Fractional Number of Days between DateTime objects in Java

下一篇: How to calculate difference between two dates in years...etc with Joda