Fractional Number of Days between DateTime objects in Java

How do I find the fractional difference in Days between two Joda-Time DateTime instances?

Days.daysBetween(start, end).getDays() gives me a round number like 10/15 etc. What i need to get is exact value like 10.15 or 15.78


You might miss minutes due to the round off, if you use Hours.hoursBetween .

Try this : (end.getMillis - start.getMillis() )/(1000*3600*24)


Subtract the time in millis and divide by number of millis per day:

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

Test

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

Output

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

Note that it's only 13 hours, not 14, because of daylight savings time.


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

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

上一篇: 如何在JavaScript中计算2个日期之间的日期名称数量

下一篇: Java中DateTime对象之间的小数天数