Storing difference between two LocalDateTime values

4.2k views Asked by At

I am trying to save the difference between two LocalDateTimes. So actually, I am looking for a class like Period which allows me to save date aswel as time (Since Period only allows me to save the date).

What class would let me do so?

3

There are 3 answers

5
assylias On BEST ANSWER

The correct way is to decompose the difference by time unit such as in this answer.


Another option would be to save the date difference in a period and the time difference in a duration but this may lead to negative units in some cases:

LocalDateTime now = LocalDateTime.now();
LocalDateTime before = now.minusMonths(1).minusDays(5).minusHours(2).minusMinutes(30);
Period p = Period.between(before.toLocalDate(), now.toLocalDate());
Duration d = Duration.between(before.toLocalTime(), now.toLocalTime());

System.out.println(p + " + " + d);

which outputs: P1M5D + PT2H30M

Corner cases: if before = now.minusMonths(1).plusDays(1).plusMinutes(30);, the duration is minus 30 minutes. This can't easily be fixed because doing an intuitive:

if (d.isNegative()) {
  p = p.minusDays(1);
  d = d.plusDays(1);
}

Can return negative days in other cases.

2
Pâris Douady On

I think you should convert both of them in millis then make a subtraction.

LocalDateTime a, b;
long timeInMillis = Math.abs(a.toDateTime().getMillis() - b.toDateTime().getMillis());

You will then get the period in milliseconds.

0
rgrebski On
 @Test
    public void durationTest(){
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime nowMinus5s = now.minusSeconds(5);

        assertThat(Duration.between(now, nowMinus5s).getSeconds()).isEqualTo(-5);
    }