Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display the number of days in every month with Java Time

I am trying to display number of days in every month of the year

LocalDate start = LocalDate.of(2016, 01, 01);
LocalDate end = start.plusYears(1);
Period everyMonth = Period.ofMonths(1);
for (;start.isBefore(end); start = start.plus(everyMonth)) {
    System.out.println(Period.between(start, start.plus(everyMonth)).getDays());
}

Why do I get 12 0s?

like image 224
Vitalie Avatar asked Feb 08 '23 18:02

Vitalie


1 Answers

You are not using correctly the Period class here. start represents the date 01/01/2016 (in dd/MM/yyyy format). When you are adding a period of 1 month, the result is the date 01/02/2016.

The period between those two dates, as defined by the Period class is "1 month". If you print the period, you will have "P1M", which is the pattern to say that:

A date-based amount of time in the ISO-8601 calendar system, such as '2 years, 3 months and 4 days'.

As such, getDays(), which return the amount of days in the period, will return 0. The result is different than the number of days between the two dates. You can convince yourself of that by printing the result of getMonths, it would return 1:

public static void main(String[] args) {
    LocalDate start = LocalDate.of(2016, 01, 01);
    Period period = Period.between(start, start.plus(Period.ofMonths(1)));
    System.out.println(period.getDays());   // prints 0
    System.out.println(period.getMonths()); // prints 1
}

Now, in your question, you want to print the number of days in every month. You can simply have the following:

for (Month month : Month.values()) {
    System.out.println(month.length(Year.now().isLeap()));
}

In Java Time, there is an enum Month for all the months, and the method length(leapYear) return the length of this month, i.e. the number of days in the month. Since this depends on whether the current year is a leap year or not, there is a boolean argument for that.

To check for the current year, we can call Year.now() and return if it's a leap year or not with isLeap().


As a side-note, if you truly wanted to print the number of days between two dates, you would need to use ChronoUnit.DAYS.between(start, end).

like image 106
Tunaki Avatar answered Feb 12 '23 11:02

Tunaki