在咨询了几个论坛之后,我最终使用下面的代码来查找时间差异。但是,我发现逻辑上存在问题(可能是我的视线吗?)。我看到11到14天和11到15天之间的差异是相同的。这怎么可能?
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
使用浮动,我看到了问题。使用时间戳似乎不是找到两个日期之间的天差的好方法。
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
展望未来,我发现确定日期差异的最确定的方法是
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)); }