-1

After searching for a while about this topic i found 3 methods of Calendar class isBefore(), isAfter() And isAfter() but this methods only returns true or false . So my question here is there a method or a way that allowed us to compare two dates and print how much they differ .

Example :

Calendar date1 = new GregorianCalendar(2020,12,01);

Calendar date1 = new GregorianCalendar(2020,12,20);

We should return 29 days .

Douf Jawad
  • 11
  • 1
  • 1
    Should we? Which timezone are you evaluating that in? – Mike 'Pomax' Kamermans Feb 14 '21 at 00:03
  • the two dates are in the same timeZone , And we should calculate the diffrence between the two in days or hours – Douf Jawad Feb 14 '21 at 00:07
  • I recommend you don’t use `Calendar` and `GregorianCalendar`. Those classes are poorly designed and long outdated. Instead use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Feb 14 '21 at 09:19
  • It may be a typo or something. From January 1 to January 20 are 19 days, not 29. Regardless of time zone. Also @Mike'Pomax'Kamermans January? Yes, the dates in the question are in January 2021. That’s how confusing `GregorianCalendar` is. – Ole V.V. Feb 14 '21 at 09:20

1 Answers1

-1

If youre not forced to use the Calendar class for this, you can get a duration easily with the LocalDate and Duration classes.

LocalDateTime now = LocalDateTime.of(2020, 12, 01);
LocalDateTime future = LocalDateTime.of(2020, 12, 20);

Duration duration = Duration.between(now, future);
long days = duration.toDays();
stelar7
  • 336
  • 1
  • 3
  • 14
  • Not exactly. Using `LocalDate` is an obvious and excellent idea. Using `Duration` with `LocalDate` does not work. On my Java 11 I get `java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Seconds`. Use for example `ChronoUnit.DAYS.between(now, future)` (yields 19). – Ole V.V. Feb 14 '21 at 09:26
  • Huh.. the more you know. The original example used LocalDateTime, where thats not an issue – stelar7 Feb 14 '21 at 17:54
  • That’s right. You can find the `Duration` between two `LocalDateTime` objects exactly because they define time of day. With two `LocalDate` objects you don’t know whether its from 17:00 on the first day until 8:00 on the second day or the other way around, so java.time refuses to give you a `Duration`. – Ole V.V. Feb 14 '21 at 18:46
  • From [the documentation of `Duration.betweem()`](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/time/Duration.html#between(java.time.temporal.Temporal,java.time.temporal.Temporal)): *he specified temporal objects must support the `SECONDS` unit.* Since a `LocalDate` doesn’t have time of day, it does not support said unit. – Ole V.V. Feb 14 '21 at 18:51