JAVA獲取一年中全部的週末

代碼以下:java

public class test {

    public static void main(String[] args) {
        String year = "2016";
        Calendar c = Calendar.getInstance();
        c.set(Integer.parseInt(year), 0, 1);
        Calendar c2 = Calendar.getInstance();
        c2.set(Integer.parseInt(year) + 1, 0, 1);
        int count = 0;
        while (c.compareTo(c2) < 0) {
            if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || c.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
                System.out.println(c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-"
                        + c.get(Calendar.DAY_OF_MONTH));
                count++;
            }
            // 日期+1
            c.add(Calendar.DATE, 1);
        }
        System.out.println("共" + count + "條記錄");
    }

}

注意:月份是從0開始計算的,因此顯示時要+1code

輸出結果:get

2016-1-2
2016-1-3
2016-1-9
2016-1-10
2016-1-16
2016-1-17
2016-1-23
2016-1-24
2016-1-30
2016-1-31
2016-2-6
2016-2-7
2016-2-13
2016-2-14
2016-2-20
2016-2-21
2016-2-27
2016-2-28
2016-3-5
2016-3-6
2016-3-12
2016-3-13
2016-3-19
2016-3-20
2016-3-26
2016-3-27
2016-4-2
2016-4-3
2016-4-9
2016-4-10
2016-4-16
2016-4-17
2016-4-23
2016-4-24
2016-4-30
2016-5-1
2016-5-7
2016-5-8
2016-5-14
2016-5-15
2016-5-21
2016-5-22
2016-5-28
2016-5-29
2016-6-4
2016-6-5
2016-6-11
2016-6-12
2016-6-18
2016-6-19
2016-6-25
2016-6-26
2016-7-2
2016-7-3
2016-7-9
2016-7-10
2016-7-16
2016-7-17
2016-7-23
2016-7-24
2016-7-30
2016-7-31
2016-8-6
2016-8-7
2016-8-13
2016-8-14
2016-8-20
2016-8-21
2016-8-27
2016-8-28
2016-9-3
2016-9-4
2016-9-10
2016-9-11
2016-9-17
2016-9-18
2016-9-24
2016-9-25
2016-10-1
2016-10-2
2016-10-8
2016-10-9
2016-10-15
2016-10-16
2016-10-22
2016-10-23
2016-10-29
2016-10-30
2016-11-5
2016-11-6
2016-11-12
2016-11-13
2016-11-19
2016-11-20
2016-11-26
2016-11-27
2016-12-3
2016-12-4
2016-12-10
2016-12-11
2016-12-17
2016-12-18
2016-12-24
2016-12-25
2016-12-31
共105條記錄
相關文章
相關標籤/搜索