Period, Duration and Instant in Java
Period, Duration and Instant are three different classes introduced since Java 8 to help us deal better with time.
- Period measures the time with days granularity. In other words, there are no hours, minutes, nor seconds. Example:
Period threeDaysPeriod = Period.ofDays(3);
System.out.println(threeDaysPeriod.getDays()); // prints 3
There are also methods ofDays, ofMonths and so on. It's noteworthy to mention that you cannot convert automatically a period of 365 days to 12 months:
Period threeDaysPeriod = Period.ofDays(365);
System.out.println(threeDaysPeriod.getMonths()); // prints 0
- Duration is similar to Period but with mcuh finer granularity of up to nanoseconds. Example:
Duration oneDay = Duration.ofDays(1);
System.out.println(oneDay.getSeconds()); // prints 86400
Note: you cannot mix Period and Duration so the following is not allowed:
Period oneDay = Period.ofDays(1);
Duration twentyFourHours = Duration.ofDays(1);
twentyFourHours.compareTo(oneDay); //Cannot compile
- Instant is for marking the current moment with granularity of up to nanoseconds. It is useful for various tasks such as measuring performance, e.g.:
Instant beginning = Instant.now();
Thread.sleep(1000); // wait one second
Instant end = Instant.now();
Duration duration = Duration.between(beginning, end);
System.out.printf("It took %d second(s).", duration.getSeconds()); // prints It took 1 second(s).
The above three classes make your life easier and the code cleaner.