java.util.Calendar getMaximum 最后一天返回错误

Ali*_*a17 1 java calendar date

我必须修复一些代码。由于某种原因,Calender.getMaximum(Calendar.DAY_OF_MONTH)2019 年 6 月返回了 31 天,而不是 30 天,因为 6 月只有 30 天。

public static int getWorkingDaysInMonth(int month, int year) {
    Calendar monthStart = Calendar.getInstance();
    Calendar monthEnd = Calendar.getInstance();
    monthStart.set(year, month, 1);
    return monthStart.getActualMaximum(Calendar.DAY_OF_MONTH);
}
Run Code Online (Sandbox Code Playgroud)

现在如你所见,我替换getMaximum()getActualMaximum(). 现在我得到了 lastday = 30 ,所以现在它是正确的。但它总是会返回正确的最后一天吗,我不想破坏任何东西。

我按以下方式调用该函数:

getWorkingDaysInMonth(5, 2019);  // 5 is June
Run Code Online (Sandbox Code Playgroud)

感谢您的评论。

deH*_*aar 5

Calendar.getMaximum() 返回传递的字段的最大数量Calendar.DAY_OF_MONTH在你的情况下是 31,因为没有一个月会有 32 天或更多
⇒ 一年中一个月可以有的最大天数
⇒ 总是输出 31,无论哪个月份已定义

Calendar.getActualMaximum() 返回指定月份(在该实例中定义的月份)实际拥有的最大天数
⇒ 该实例的月份在该实例的年份中拥有的天数
⇒ 将为不同年份的不同月份输出不同的值

这应该意味着Calendar.getActualMaximum()每年的每个月都应该工作。

我将java.time为此使用,请参阅以下示例:

带计算的长版本:

public static long getWorkingDaysInMonth(int month, int year) {
    // create a LocalDate that represents the 1st of the given month in the given year
    LocalDate firstOfMonth = LocalDate.of(year, month, 1);
    // and create one that represents the 1st of the following month
    LocalDate firstOfNextMonth = firstOfMonth.plusMonths(1);
    // return the amount of days between (the second argument is exclusive)
    return ChronoUnit.DAYS.between(firstOfMonth, firstOfNextMonth);
}
Run Code Online (Sandbox Code Playgroud)

简短版本:

public static long getWorkingDaysInMonth(int month, int year) {
    // directly return the amount of days of the specified month
    return YearMonth.of(year, month).lengthOfMonth();
}
Run Code Online (Sandbox Code Playgroud)

或者

public static long getWorkingDaysInMonth(int month, int year) {
    // directly return the amount of days of the specified month
    return LocalDate.of(year, month, 1).lengthOfMonth();
}
Run Code Online (Sandbox Code Playgroud)

注意:
无论哪个版本都必须通过它来调用

int amountOfDays = getWorkingDaysInMonth(6, 2019);
Run Code Online (Sandbox Code Playgroud)

因为在 中java.time,月份从 1 开始,就像现实生活中一样;-)

  • 或者跳过计算并使用 return LocalDate.of(year, Month, 1).lengthOfMonth();` (3认同)