1 public static void printWeeks() { 2 SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd"); 3 Calendar calendar = Calendar.getInstance(); 4 calendar.set(Calendar.DATE, 1); 5 int month = calendar.get(Calendar.MONTH); 6 int count = 0; 7 while (calendar.get(Calendar.MONTH) == month) { 8 if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { 9 StringBuilder builder = new StringBuilder();10 builder.append("week:");11 builder.append(++count);12 builder.append(" (");13 builder.append(format.format(calendar.getTime()));14 builder.append(" - ");15 calendar.add(Calendar.DATE, 6);16 builder.append(format.format(calendar.getTime()));17 builder.append(")");18 System.out.println(builder.toString());19 }20 calendar.add(Calendar.DATE, 1);21 }22 }
打印结果:
月:
1 Calendar calendar = Calendar.getInstance(); 2 int year = calendar.get(Calendar.YEAR); 3 calendar.clear(); 4 //当年元月 5 calendar.set(Calendar.YEAR, year); 6 calendar.set(Calendar.MONTH, 0); 7 8 while (calendar.get(Calendar.YEAR) == year) { 9 String outPrint = "";10 outPrint += year+"年";11 int month = calendar.get(Calendar.MONTH);12 //月起始时间13 calendar.set(GregorianCalendar.DAY_OF_MONTH, 1); 14 String monthStart = format.format(calendar.getTime());15 outPrint += monthStart;16 outPrint += " - ";17 //月终止时间18 calendar.set( Calendar.DATE, 1 ); 19 calendar.roll(Calendar.DATE, - 1 );20 String monthEnd = format.format(calendar.getTime());21 outPrint += monthEnd;22 System.out.println(outPrint);23 calendar.add(Calendar.MONTH, 1);24 }
打印结果