2016年5月12日 星期四

Calendar的運用範例(13號星期五)

int start = 1950;
int end = 2050;
if (start > end) {
    System.err.println("起始年>結束年");
    System.exit(0);
}
    
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, 13);// 寫死的13號
List<Integer> months = Arrays.asList(Calendar.JANUARY, Calendar.FEBRUARY, Calendar.MARCH, Calendar.APRIL,
        Calendar.MAY, Calendar.JUNE, Calendar.JULY, Calendar.AUGUST, Calendar.SEPTEMBER, Calendar.OCTOBER,
        Calendar.NOVEMBER, Calendar.DECEMBER);
    
for (int i = start; i < end + 1; i++) {
    String[] ymd = null;
    // int count = 0;
    cal.set(Calendar.YEAR, i);
    for (int j = 0; j < months.size(); j++) {
        cal.set(Calendar.MONTH, j);
    
        // 如果是星期五
        if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
            ymd = df.format(cal.getTime()).split("/");
            System.out.println(ymd[0] + "年" + ymd[1] + "月" + ymd[2] + "日");
            // count++;
        }
    }
    System.out.println("-----------------------------");
    // System.out.println("#######################################");
    // if (count == 3) {
    // System.out.println("一年有3次13號星期五的是" + ymd[0] + "年");
    // }
}

※註解的部分是判斷一年中13號星期五的次數用的

沒有留言:

張貼留言