0

How to calculate the full difference between two ZonedDateTime instances with same ZoneId? In other words difference in all time unites.

Using Java 8 and don't what to use any third party library like Joda or something else.

ZonedDateTime start = ZonedDateTime.parse("2007-05-11T15:30:00Z");
ZonedDateTime end = ZonedDateTime.parse("2008-03-01T13:00:00Z");

Duration.between(start, end); // PT7077H30M
Period.between(start.toLocalDate(), end.toLocalDate()) // P9M19D

Using Joda-Time

import org.joda.time.DateTime;
import org.joda.time.Period;

DateTime start = DateTime.parse("2007-05-11T15:30:00Z");
DateTime end = DateTime.parse("2008-03-01T13:00:00Z");

Period period = new Period(start, end); // P9M2W4DT21H30M

How get a same result using standard Date/Time API?

Edgar Asatryan
  • 687
  • 9
  • 13
  • 2
    `Duration.between(start, end)` ... https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html#between-java.time.temporal.Temporal-java.time.temporal.Temporal- – Brad Jul 19 '19 at 16:26
  • I already made an answer and then you closed it, very sad. – Alan Sereb Jul 19 '19 at 16:31
  • I re-opened it for you. But I think, there will be no answer besides doing some coding with `Period` and `Duration`. – Seelenvirtuose Jul 19 '19 at 16:51
  • @Brad How get months and days from `Duration`? `Period` gives `9 months 19 days`. – Edgar Asatryan Jul 19 '19 at 16:58
  • I’m confused. Your code example is using *java.time*. But the you are talking about *Joda-Time*. – Basil Bourque Jul 19 '19 at 17:41
  • 1
    @BasilBourque I'm asking how to achieve same result as in Joda, but using `java.time` . – Edgar Asatryan Jul 19 '19 at 17:44
  • Do you mean literally that string as output? Edit your Question to clarify. Also, this topic has been addressed multiple times already. Search Stack Overflow before posting. – Basil Bourque Jul 19 '19 at 17:46
  • 1
    Tip: It rarely makes sense to mix years-months-days with hours-minutes-seconds (think about it). But if you insist on that, see the *ThreeTen-Extra* library with its `PeriodDuration` class. – Basil Bourque Jul 19 '19 at 17:49
  • @BasilBourque I didn't mean the string, but you can think as it. I've searched before posting and did not find anything suitable, all the are posting to calculate difference in a single `ChronoUnit`. – Edgar Asatryan Jul 19 '19 at 17:51
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/196724/discussion-between-edgar-asatryan-and-basil-bourque). – Edgar Asatryan Jul 19 '19 at 17:59

0 Answers0