java.time.LocalDateTime
was not created to represent a difference between two dates. There are java.time.Period
and java.time.Duration
that should be used for it (see Oracle docs).
A Duration
measures an amount of time using time-based values
(seconds, nanoseconds). A Period
uses date-based values (years,
months, days).
They both have a convenient .between()
method, which you could use like this:
Duration diff = Duration.between(ZonedDateTime.now(ZoneId.systemDefault()), endTime);
The reason why there are no combined classes to represent duration as years, months, days AND hours, minutes, seconds is that a day could be 24 or 25 hours depending on Daylight saving time. So
A Duration
of one day is exactly 24 hours long. A Period
of one day, when added to a ZonedDateTime
, may vary according to the time zone. For example, if it occurs on the first or last day of daylight saving time.
I would suggest you to use the Duration
class and if you want to pretty print it, you have to do it manually like this (thanks to this answer):
System.out.println(diff.toString()
.substring(2)
.replaceAll("(\\d[HMS])(?!$)", "$1 ")
.toLowerCase());
This will print something like 370h 24m 14.645s
. If you want days, months and years, you would have to calculate them from seconds and print.
If you're using Java 9+ there are methods to get number of days, hours, minutes and seconds in the duration:
System.out.println(String.format("%sd %sh %sm %ss",
diff.toDaysPart(),
diff.toHoursPart(),
diff.toMinutesPart(),
diff.toSecondsPart()));