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

时间:2015-09-14 22:16:32

标签: java jodatime

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

Days.daysBetween(start,end).getDays()给我一个像10/15等的数字。我需要得到的是精确值,如10.15或15.78

4 个答案:

答案 0 :(得分:1)

如果您使用Hours.hoursBetween。

,您可能会因为四舍五入而错过分钟

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

答案 1 :(得分:0)

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

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个小时。

答案 2 :(得分:0)

感谢评论的输入,我使用:

让它精确到秒
def face_normal(face):
    vtxface = cmds.polyListComponentConversion(face, tvf = True)
    xes = cmds.polyNormalPerVertex(vtxface, q=True, x =True)
    yes = cmds.polyNormalPerVertex(vtxface, q=True, y =True)
    zes = cmds.polyNormalPerVertex(vtxface, q=True, z =True)
    divisor = 1.0 / len(xes)
    return sum(xes)* divisor, sum(yes)  * divisor, sum(zes) * divisor

答案 3 :(得分:0)

要获得带分数的天数,请以满足您的精度要求的足够小的单位来计算差异,然后在进行除法转换为天数之前将其转换为double

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

此代码段输出:

  

天数差异为87.5

我们需要提供正确的时区,以考虑到夏令时(DST)的过渡。在我的示例中,这两天都属于欧盟一年中的标准时间,因此12小时等于0.5天。如果我为date2选择的日期是4月初,而夏季开始之后,情况就不是这样了。例如:

    DateTime date2 = new DateTime(1997, 4, 1, 12, 0, zone);
  

以天为单位的差异为90.45833333333333

由于int仅保留了这么多秒,因此该代码最多可以使用68年。如果需要更长的时间跨度,请考虑使用分钟或小时而不是秒。如果您传递的两个日期相距太远,则Joda-Time会很友好地引发异常,而不是默认给您错误的结果。

此答案是在this duplicate question之际写的,示例日期时间是从那里获取的。