The java.time.Period and java.time.Duration classes are designed to contain an amount of time:
- A Period object contains an amount of time in units of years, months, and days
- A Duration object contains an amount of time in hours, minutes, seconds, and nanoseconds
The following code demonstrates their creation and usage with LocalDateTime class but the same methods exist in LocalDate classes (for Period) and LocalTime (for Duration):
LocalDateTime ldt1 = LocalDateTime.parse("2020-02-23T20:23:12");
LocalDateTime ldt2 = ldt1.plus(Period.ofYears(2));
System.out.println(ldt2); //prints: 2022-02-23T20:23:12
The following methods work the same way:
LocalDateTime ldt = LocalDateTime.parse("2020-02-23T20:23:12");
ldt.minus(Period.ofYears(2));
ldt.plus(Period.ofMonths(2));
ldt.minus(Period.ofMonths(2));
ldt.plus(Period.ofWeeks(2));
ldt.minus(Period.ofWeeks(2));
ldt.plus(Period.ofDays(2));
ldt.minus(Period.ofDays(2));
ldt.plus(Duration.ofHours(2));
ldt.minus(Duration.ofHours(2));
ldt.plus(Duration.ofMinutes(2));
ldt.minus(Duration.ofMinutes(2));
ldt.plus(Duration.ofMillis(2));
ldt.minus(Duration.ofMillis(2));
Some other methods of creating and using objects of Period are demonstrated by the following code:
LocalDate ld1 = LocalDate.parse("2020-02-23");
LocalDate ld2 = LocalDate.parse("2020-03-25");
Period period = Period.between(ld1, ld2);
System.out.println(period.getDays()); //prints: 2
System.out.println(period.getMonths()); //prints: 1
System.out.println(period.getYears()); //prints: 0
System.out.println(period.toTotalMonths()); //prints: 1
period = Period.between(ld2, ld1);
System.out.println(period.getDays()); //prints: -2
Objects of Duration can be similarly created and used:
LocalTime lt1 = LocalTime.parse("10:23:12");
LocalTime lt2 = LocalTime.parse("20:23:14");
Duration duration = Duration.between(lt1, lt2);
System.out.println(duration.toDays()); //prints: 0
System.out.println(duration.toHours()); //prints: 10
System.out.println(duration.toMinutes()); //prints: 600
System.out.println(duration.toSeconds()); //prints: 36002
System.out.println(duration.getSeconds()); //prints: 36002
System.out.println(duration.toNanos()); //prints: 36002000000000
System.out.println(duration.getNano()); //prints: 0
There are many other helpful methods in Period and Duration classes. If you have to work with dates, we recommend you to read the API of this class and other classes of java.time package and its sub-packages.