Period Class Example In Java 8

Period and Duration are two other important classes introduced in java 8 under java.time package.  As Period uses date based values (years, months, days) while a Duration uses seconds or nanoseconds to define an amount of time. A Period is the amount of time between two LocalDate. It is same concept like Duration which is quantity or amount of time between two Instant. And this have same kind of method as Duration but work with LocalDate instead on Instant. Like Durations, Periods can contain negative values if the end point occurs before the starting point.

                                              Period Example:

If I say when Sardar Patel was born? I can create Period like below.

I am creating a Period between his date of birth and now, until is method which is used to create Period of time until now. And If I want to number of time passed in years I need to call getYears() method.

I can also call until method with special unit ChronoUnit.DAYS then it will return me long which is number of days since Sardar Patel was born.

A Period (java.time.Period package) is the amount of time between two LocalDate ,measuring time in years, months and days. Let see Period by different example:

1) Period Example:

Output:

2) Period Example:

 Sardar Patel was born October 31st,1875. If I want to know amount of time in Years, month and days since Sardar Patel was born? I can create Period like below.

I am creating a Period between his date of birth and now, until is method which is used to create Period of time until now. And If I want to number of time passed in years I need to call getYears() method.

Output:

 

I can also call until method with special unit ChronoUnit.DAYS then it will return me long which is number of days since Sardar Patel was born.

Output:

 

Check Reference:

Leave a Reply

Your email address will not be published. Required fields are marked *