calculate time between dates java code example

Example 1: calculate time java

System.out.println(LocalTime.now());

Example 2: date difference in minutes java

long diff = d2.getTime() - d1.getTime();//as given

long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);

Example 3: java localdate subtract two dates

@Test
public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() {
    LocalDate now = LocalDate.now();
    LocalDate sixDaysBehind = now.minusDays(6);
 
    Period period = Period.between(now, sixDaysBehind);
    int diff = period.getDays();
 
    assertEquals(diff, 6);
}

Tags:

Java Example