用 Java 时间显示每个月的天数

Display the number of days in every month with Java Time

我正在尝试显示一年中每个月的天数

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());
}

为什么我得到 12 个 0?

除了一件事你做对了所有事情。您尝试打印期间中的天数,但由于您总是在日期上加上 1 个月,期间为 0 years, 1 month, 0 days。当您调用 getDays() 时,它 returns 期间的天数为 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)));

您没有正确使用此处的 Period class。 start 表示日期 01/01/2016(采用 dd/MM/yyyy 格式)。当您添加 1 个月的期间时,结果是日期 01/02/2016.

这两个日期之间的时间段,如 Period class is "1 month". If you print the period, you will have "P1M" 所定义的那样:

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

因此,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,它将 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
}

现在,在您的问题中,您想要打印每个月的天数。您可以简单地拥有以下内容:

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

在Java的时候,有一个枚举Month for all the months, and the method length(leapYear)return这个月的长度,即这个月的天数。由于这取决于当前年份是否为闰年,因此有一个布尔值参数。

要检查当前年份,我们可以调用 Year.now() and return if it's a leap year or not with isLeap()


附带说明一下,如果您真的想打印两个日期之间的天数,则需要使用 ChronoUnit.DAYS.between(start, end).