Period Util

Description

The Date-Time API provides methods to compute the elapsed period between two dates and times.

We can use the until(end_date_or_time, time_unit) method on one of the datetime-related classes, for example, LocalDate, LocalTime, LocalDateTime, ZonedDateTime, etc.

Example


import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Month;
import java.time.temporal.ChronoUnit;
//from   www.ja v  a2 s  . c  om
public class Main {

  public static void main(String[] args) {
    LocalDate ld1 = LocalDate.of(2014, Month.JANUARY, 7);
    LocalDate ld2 = LocalDate.of(2014, Month.MAY, 18);

    LocalTime lt1 = LocalTime.of(7, 0);
    LocalTime lt2 = LocalTime.of(9, 30);

    long days = ld1.until(ld2, ChronoUnit.DAYS);
    System.out.println(days);
    long hours = lt1.until(lt2, ChronoUnit.HOURS);
    System.out.println(hours);
    long minutes = lt1.until(lt2, ChronoUnit.MINUTES);
    System.out.println(minutes);
  }
}

The code above generates the following result.





















Home »
  Java Date Time »
    Tutorial »




Java Date Time Tutorial