Java中的日期差异计算 [英] Date difference calculation in Java

查看:157
本文介绍了Java中的日期差异计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算两个日期之间的差异。
目前,我在做:

I want to calculate the difference between two dates. Currently, I am doing:

Calendar firstDate = Calendar.getInstance();
firstDate.set(Calendar.DATE, 15);
firstDate.set(Calendar.MONTH, 4);
firstDate.get(Calendar.YEAR);

int diff = (new Date().getTime - firstDate.getTime)/(1000 * 60 * 60 * 24)

这给我输出0.但是我希望当新的Date()为15时,我应该得到输出0.当前的新日期是14.它使我进一步的计算错误我很困惑如何解决这个。请建议。

This gives me output 0. But I want that I should get the output 0 when the new Date() is 15. Currently the new date is 14. It makes my further calculation wrong and I am confused how to resolve this. Please suggest.

推荐答案


找出两个日期之间的差异并不像
减去两个日期并将结果除以(24 * 60 * 60 *
1000)。

Finding the difference between two dates isn't as straightforward as subtracting the two dates and dividing the result by (24 * 60 * 60 * 1000). Infact, its erroneous!



/* Using Calendar - THE CORRECT (& Faster) WAY**/  
//assert: startDate must be before endDate  
public static long daysBetween(final Calendar startDate, final Calendar endDate) {  
 int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;  
 long endInstant = endDate.getTimeInMillis();  
 int presumedDays = (int) ((endInstant - startDate.getTimeInMillis()) / MILLIS_IN_DAY);  
 Calendar cursor = (Calendar) startDate.clone();  
 cursor.add(Calendar.DAY_OF_YEAR, presumedDays);  
 long instant = cursor.getTimeInMillis();  
 if (instant == endInstant)  
  return presumedDays;  
 final int step = instant < endInstant ? 1 : -1;  
 do {  
  cursor.add(Calendar.DAY_OF_MONTH, step);  
  presumedDays += step;  
 } while (cursor.getTimeInMillis() != endInstant);  
 return presumedDays;  
}  

您可以阅读更多此处

这篇关于Java中的日期差异计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆