Java Period between two Dates

By Arvind Rai, November 22, 2022
On this page we will learn to find Period between two given dates in Java application.
1. Java Period is a date-based amount of time in the ISO-8601 calendar system. The value of Period can be '3 years, 4 months and 10 days'.
2. The Period is an amount of time in terms of years, months and days where as Duration is time-based equivalent to the Period class.
3. The supported units of Period are YEARS, MONTHS and DAYS. All fields are always there but it is possible that their values may be zero.
4. On this page we will learn to find Period between two dates. The Period class has following method.
static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive) 
Returns a Period consisting the number of years, months and days between two days.
The parameters are start date and end date as LocalDate.

Between LocalDate

Find the code to get Period between two LocalDate.
LocalDate ld1 = LocalDate.parse("2021-11-15");
LocalDate ld2 = LocalDate.parse("2022-10-15");

Period p = Period.between(ld1, ld2);
System.out.println(p); 

Between LocalDateTime

To find the Period between two LocalDateTime, we need to convert LocalDateTime into LocalDate.
LocalDateTime ldt1 = LocalDateTime.parse("2021-11-15T13:15:30");
LocalDateTime ldt2 = LocalDateTime.parse("2022-10-15T13:15:30");

LocalDate ld1 = LocalDate.of(ldt1.getYear(), ldt1.getMonth(), ldt1.getDayOfMonth());
LocalDate ld2 = LocalDate.of(ldt2.getYear(), ldt2.getMonth(), ldt2.getDayOfMonth());

Period p = Period.between(ld1, ld2); 

Between Instant

To find the Period between two Instant, we need to convert Instant into LocalDate.
Instant instant1 = Instant.parse("2021-11-15T00:00:00Z");
ZoneId zone = ZoneId.of("Asia/Kolkata");
LocalDate ld1 = LocalDate.ofInstant(instant1, zone);

Instant instant2 = Instant.parse("2022-10-15T00:00:00Z");
LocalDate ld2 = LocalDate.ofInstant(instant2, zone);	

Period p = Period.between(ld1, ld2); 

Between ZonedDateTime

To find the Period between two ZonedDateTime, we need to convert ZonedDateTime into LocalDate.
ZonedDateTime zonedDateTime1 = ZonedDateTime.parse("2021-11-15T13:15:30+05:30[Asia/Calcutta]");
ZonedDateTime zonedDateTime2 = ZonedDateTime.parse("2022-10-15T13:15:30+05:30[Asia/Calcutta]");

LocalDate ld1 = zonedDateTime1.toLocalDate();
LocalDate ld2 = zonedDateTime2.toLocalDate();

Period p = Period.between(ld1, ld2); 

Reference

Class Period
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us