Display the number of days in each month with Java Time

I try to show the number of days in each 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 am I getting 12 0?

+4
source share
2 answers

You are not using the class correctly Periodhere. startrepresents the date 01/01/2016(in format dd/MM/yyyy). When you add a period of 1 month, the result will be a date 01/02/2016.

The period between these two dates, determined by the class Period, is “1 month”. If you print a period, you will get "P1M"that is a template to say that:

Time in the ISO-8601 database based on a date, for example, "2 years, 3 months, and 4 days."

, getDays(), , 0. . , getMonths, 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
}

, , . :

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

Java Time enum Month , length(leapYear) , . , , .

, Year.now() , isLeap().


, , ChronoUnit.DAYS.between(start, end).

+6

, . , 1 , 0 years, 1 month, 0 days. getDays(), , 0.

final Period period = Period.between(start, start.plus(everyMonth);
System.out.println(period.getDays()); // 0
System.out.println(period.getMonths()); // 1

, :

System.out.println(ChronoUnit.DAYS.between(start, start.plus(everyMonth)));
+2

Source: https://habr.com/ru/post/1628105/


All Articles