Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the number of days in a period?

Tags:

java

java-8

For the following Period calculation:

Period.between(LocalDate.of(2015, 8, 1), LocalDate.of(2015, 9, 2)) 

the result is:

P1M1D 

This is equivalent to 31 days + 1 day = 32 days.

For this Period:

Period.between(LocalDate.of(2015, 8, 1), LocalDate.of(2015, 10, 2)) 

the result is:

P2M1D 

This is equivalent to: 31 days (in August) + 30 days (in September) + 1 (in October) = 62 days

Is there a method in the java.time package which will give the number of days in a Period? I can't find one. Not sure if I have overlooked anything or if it is just plain not there.

like image 927
M.K. Avatar asked Jun 14 '15 19:06

M.K.


1 Answers

From the documentation:

To define an amount of time with date-based values (years, months, days), use the Period class. The Period class provides various get methods, such as getMonths, getDays, and getYears.To present the amount >of time measured in a single unit of time, such as days, you can use the ChronoUnit.between method.

LocalDate today = LocalDate.now(); LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);  Period p = Period.between(birthday, today); long p2 = ChronoUnit.DAYS.between(birthday, today); System.out.println("You are " + p.getYears() + " years, " + p.getMonths() +                    " months, and " + p.getDays() +                    " days old. (" + p2 + " days total)"); 

The code produces output similar to the following:

You are 53 years, 4 months, and 29 days old. (19508 days total) 
like image 124
Saket Mittal Avatar answered Oct 03 '22 20:10

Saket Mittal