我想知道两个日期之间的天数。
下面是我尝试过的逻辑
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
final Date endDate = cal.getTime();
final Date currentDate = new Date();
System.out.println(TimeUnit.MILLISECONDS.toDays(endDate.getTime() - currentDate.getTime()));它总是打印0。期望是打印1。有什么想法吗?
发布于 2021-10-27 08:27:18
一天是24*60*60*1000毫秒。
endDate.getTime() - currentDate.getTime()总是比这更短。
因此,您应该始终将结果加1:
System.out.println(TimeUnit.MILLISECONDS.toDays(endDate.getTime() - currentDate.getTime()) + 1);发布于 2021-10-27 08:28:04
endDate.getTime() - currentDate.getTime()的结果只比一天少几毫秒,所以结果四舍五入为0。
如果你用currentDate初始化你的日历,你会得到预期的结果:
final Date currentDate = new Date();
final Calendar cal = Calendar.getInstance();
cal.setTime(currentDate);
cal.add(Calendar.DATE, 1);
final Date endDate = cal.getTime();
System.out.println(TimeUnit.MILLISECONDS.toDays(endDate.getTime() - currentDate.getTime()));https://stackoverflow.com/questions/69735028
复制相似问题