在java中找到日子差异 [英] Finding days difference in java
问题描述
在咨询了几个论坛后,我最终使用下面的代码来查找日期差异。但是,我看到一个逻辑问题(可能是我的眼光?)。我看到,11到14和11到15之间的日差是一样的。如何可能?
After consulting a few forums, I ended up using the code below to find the days difference. But, I see a problem with the logic (may be it's my over sight?). I see that for days difference between 11 to 14 and 11 to 15 is same. How is it possible?
Date createdDate = new Date((2013 + 1900), (1 + 1), 11);
Date expirationDate = new Date((2013 + 1900), (1 + 1), 11);
for (int i = 11; i < 20; i++) {
expirationDate.setDate(i);
System.out.println("11 to " + i + " = "
+ (int) (expirationDate.getTime() - createdDate.getTime())
/ (1000 * 60 * 60 * 24));
}
输出是:
11 to 11 = 0
11 to 12 = 1
11 to 13 = 2
11 to 14 = 3
11 to 15 = 3
11 to 16 = 4
11 to 17 = 5
11 to 18 = 6
11 to 19 = 7
推荐答案
使用float,我看到问题。使用时间戳似乎并不是找到两个日期之间的差距的好方法。
Using float, I see the problem. Using timestamp doesn't seem like a good approach to finding the days difference between 2 dates.
11至11 = 0.0
11至12 = 1.0
11至13 = 2.0
11至14 = 3.0
11至15 = 3.9583333
11至16 = 4.9583335
11至17 = 5.9583335
11至18 = 6.9583335
11至19 = 7.9583335
11 to 11 = 0.0
11 to 12 = 1.0
11 to 13 = 2.0
11 to 14 = 3.0
11 to 15 = 3.9583333
11 to 16 = 4.9583335
11 to 17 = 5.9583335
11 to 18 = 6.9583335
11 to 19 = 7.9583335
展望未来,我发现确定日期差异的最确定方式为
Going forward, I find the most conclusive way to determine the date difference as
Calendar cre_calendar = new GregorianCalendar((2013), (1), 11);
Calendar exp_calendar = new GregorianCalendar((2013), (1), 19);
Calendar maxDays = new GregorianCalendar(((2013)), (12), 31);
if (exp_calendar.get(Calendar.DAY_OF_YEAR) < cre_calendar
.get(Calendar.DAY_OF_YEAR)) {
System.out
.println((exp_calendar.get(Calendar.DAY_OF_YEAR) + maxDays
.get(Calendar.DAY_OF_YEAR))
- cre_calendar.get(Calendar.DAY_OF_YEAR));
} else {
System.out.println((exp_calendar.get(Calendar.DAY_OF_YEAR))
- cre_calendar.get(Calendar.DAY_OF_YEAR));
}
这篇关于在java中找到日子差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!