Period Between
Description
The Date-Time API provides methods to compute the elapsed period between two dates and times.
We can use the between()
method on one of the constants in the ChronoUnit enum.
ChronoUnit enum between()
method takes two datetime objects and returns a long.
If the second argument occurs before the first one, it returns a negative amount.
The returned amount is the complete number of units between two dates and times. For example, calling HOURS.between() on 06:00 and 09:30 the return value is 3, not 3.5. while MINUTES.between on 06:00 and 09:30 returns 210.
Example
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Month;
import java.time.temporal.ChronoUnit;
//from www. ja va2s . c o m
public class Main {
public static void main(String[] args) {
LocalDate ld1 = LocalDate.of(2014, Month.JANUARY, 7);
LocalDate ld2 = LocalDate.of(2014, Month.MAY, 21);
long days = ChronoUnit.DAYS.between(ld1, ld2);
System.out.println(days);
LocalTime lt1 = LocalTime.of(6, 0);
LocalTime lt2 = LocalTime.of(9, 30);
long hours = ChronoUnit.HOURS.between(lt1, lt2);
System.out.println(hours);
long minutes = ChronoUnit.MINUTES.between(lt1, lt2);
System.out.println(minutes);
}
}
The code above generates the following result.