【问题标题】:calendar.getActualMaximum(Calendar.WEEK_OF_YEAR) returns 52 for months 1-11 and returns 53 for month 12calendar.getActualMaximum(Calendar.WEEK_OF_YEAR) 在第 1-11 个月返回 52,在第 12 个月返回 53
【发布时间】:2016-04-06 12:03:58
【问题描述】:

我正在使用 calendar.getActualMaximum(Calendar.WEEK_OF_YEAR) 来获取给定年份的总周数。这是我正在使用的功能:

public static void main(String[] args) {

    for(int i=2012; i<=2016; i++) {
        System.out.println("Year : " + i + ", Total Weeks : " + getNumWeeksForYear(i));
    }

}
public static int getNumWeeksForYear(int year) {  
    Calendar c = Calendar.getInstance();           
    c.set(year, 12, 31); //issue
    c.setFirstDayOfWeek(Calendar.MONDAY );
    return c.getActualMaximum(Calendar.WEEK_OF_YEAR);   
}
c.set(year, 12, 31) 的输出: 年份 : 2012, 总周数 : 52 年份 : 2013, 总周数 : 52 年份 : 2014, 总周数 : 52 年份 : 2015, 总周数 : 52 年份 : 2016, 总周数 : 53 c.set(year, 1, 31) 的输出: 年份 : 2012, 总周数 : 53 年份 : 2013, 总周数 : 52 年份 : 2014, 总周数 : 52 年份 : 2015, 总周数 : 52 年份 : 2016, 总周数 : 52

当日历月设置为 12 月时,我无法弄清楚为什么一年中的总周数会有所不同。我尝试使用 1-12 月,对于 1-11 月,周数相同但更改为12 月。从实验中我可以预测它只发生在闰年。

我参考了以下链接:Calendar.getActualMaximum(Calendar.WEEK_OF_YEAR) weirdness

但这并不能回答我的问题。

【问题讨论】:

    标签: java date calendar


    【解决方案1】:

    第一个月是

    private static final int JANUARY = 0;
    

    最后一个月是

    private static final int DECEMBER = 11;
    

    这意味着月份 12 是下一年的第一个月。

    【讨论】:

    • @Peter:谢谢。你是对的。但如果我使用 11(2016 年 12 月),它返回 52 周,而 2016 年有 53 周。获取总周数的正确方法是什么?
    【解决方案2】:

    这里的月份索引像这样从 0 开始。

    JANUARY=0, FEBRUARY=1,.., DECEMBER=11
    

    所以在 11 之前它会返回正确的值

    示例代码:

    public static int getNumWeeksForYear(int year) {  
            Calendar c = Calendar.getInstance();           
            c.set(year, 11,31); //issue
            c.setFirstDayOfWeek(Calendar.MONDAY );
            return c.getActualMaximum(Calendar.WEEK_OF_YEAR);   
        }
    

    输出:

    Year : 2012, Total Weeks : 53
    Year : 2013, Total Weeks : 52
    Year : 2014, Total Weeks : 52
    Year : 2015, Total Weeks : 52
    Year : 2016, Total Weeks : 52
    

    如果你给大于 11

    c.set(year, 14,31);
    

    输出:

    Year : 2012, Total Weeks : 52
    Year : 2013, Total Weeks : 52
    Year : 2014, Total Weeks : 52
    Year : 2015, Total Weeks : 52
    Year : 2016, Total Weeks : 53
    

    计算一年中的准确周数see this example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-30
      • 2020-01-30
      • 2011-09-29
      • 2020-07-26
      • 1970-01-01
      • 2011-12-05
      相关资源
      最近更新 更多