- package com.ebocy.redmine;
- import java.util.Calendar;
- public class Test {
- public static void main(String[] args) {
- int year = 2012;
- int month = 1;
- int[][] cal = getCalendar(year, month);
- System.out.println("\\t\\t\\t" + year + "年" + (month + 1) + "月");
- System.out.println("周\\t星期天\\t星期一\\t星期二\\t星期三\\t星期四\\t星期五\\t星期六");
- for (int j = 0; j < cal.length; j++) {
- int[] week = cal[j];
- int z = week[0];
- System.out.print(z + "周\\t");
- for (int i = 0; i < week.length - 1; i++) {
- // 第一周
- if (z == 1) {
- int d = week[i + 1];
- // 去年日期
- if (d > 7) {
- System.out.print("12月" + d + "日\\t");
- } else {
- System.out.print((month + 1) + "月" + d + "日\\t");
- }
- } else {
- int d = week[i + 1];
- // 下月日期
- if (j == 4 && d < 7) {
- System.out.print((month + 2) + "月" + d + "日\\t");
- // 上月日期
- } else if (j == 0 && d > 20) {
- System.out.print((month) + "月" + d + "日\\t");
- } else {
- System.out.print((month + 1) + "月" + d + "日\\t");
- }
- }
- }
- System.out.println();
- }
- }
- public static int[][] getCalendar(int year, int month) {
- int[][] cal = new int[5][8];
- Calendar calendar = Calendar.getInstance();
- calendar.set(year, month, 1);
- for (int i = 0; i < 5; i++) {
- int[] days = new int[8];
- days[0] = calendar.get(Calendar.WEEK_OF_YEAR);
- int week = calendar.get(Calendar.DAY_OF_WEEK);
- for (int j = 1; j < days.length; j++) {
- if (j >= week) {
- days[j] = calendar.get(Calendar.DAY_OF_MONTH);
- calendar.add(Calendar.DAY_OF_MONTH, 1);
- } else {
- Calendar temp = (Calendar) calendar.clone();
- temp.add(Calendar.DAY_OF_MONTH, -(week - j));
- days[j] = temp.get(Calendar.DAY_OF_MONTH);
- }
- }
- cal[i] = days;
- }
- return cal;
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/280520133629.html
来源: http://www.codesnippet.cn/detail/280520133629.html