0

Hi wanted to get the number of days in between dates.

Below is the logic I tried

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

It is always printing 0. Expectation is to print 1. Any ideas?

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
sree
  • 868
  • 2
  • 12
  • 35
  • 1
    Side note: Please avoid the outdated (pun intended, sorry) `java.util.Date` and `Calendar` classes. They have a lot of known issues and have been replaced by the classes in the [`java.time`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/package-summary.html) package. – Hulk Oct 27 '21 at 08:24
  • 1
    I changed to java.time and it is working as expected thanks – sree Oct 27 '21 at 08:36
  • Both, `endDate` and `currentDate` should use the same base i.e. it should be `final Calendar cal = Calendar.getInstance(); final Date currentDate = cal.getTime(); cal.add(Calendar.DATE, 1); final Date endDate = cal.getTime();` – Arvind Kumar Avinash Oct 27 '21 at 08:39
  • I recommend you don’t use `Calendar` and `Date`. Those classes are poorly designed and long outdated. Instead since Java 8 use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Oct 28 '21 at 18:14

2 Answers2

1

A day is 24*60*60*1000 milliseconds.

endDate.getTime() - currentDate.getTime() is always shorter than that.

So you should always add 1 to the result:

System.out.println(TimeUnit.MILLISECONDS.toDays(endDate.getTime() - currentDate.getTime()) + 1);
hata
  • 11,633
  • 6
  • 46
  • 69
  • 1
    This does not answer the question. Check the correct answer in [my comment](https://stackoverflow.com/questions/69735028/timeunit-java-returning-zero-days#comment123264038_69735028). – Arvind Kumar Avinash Oct 27 '21 at 08:41
  • *A day is `24*60*60*1000` milliseconds.* Incorrect. A day may be longer or shorter than 24 hours. – Ole V.V. Oct 27 '21 at 10:33
0

The result of endDate.getTime() - currentDate.getTime() is just a few millisecond less than a day, so the result is rounded to 0.

You would have the expected result if you initialize your calendar with the 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()));
obourgain
  • 8,856
  • 6
  • 42
  • 57