Java 使用Calendar类输出指定年份和月份的日历

public class CalendarDemo {

public static void main(String[] args) {
    for (int i = 1; i <= 12; i++) {
        printCalender(2020, i);
    }
}

/**
 * 打印日历
 *
 * @param year
 * @param month
 */
public static void printCalender(int year, int month) {

    Calendar calendar = Calendar.getInstance();
    //Java中月份从0月开始计数
    calendar.set(year, month - 1, 1);
    //Java中规定了每周第一天是星期日,所以星期日=0,星期一=1…星期六=6
    int startDay = calendar.get(Calendar.DAY_OF_WEEK); //求本周第一天是星期几
    int count = startDay - 1; //第一周的初始计数
    int maxDay = maxDayInMonth(year, month);
    System.out.println("\n"+year + "年" + month + "月日历:");
    System.out.println("日\t一\t二\t三\t四\t五\t六");
    fillSpace(startDay);
    for (int i = 1; i <= maxDay; i++) {
        System.out.print(i + "\t"); //使用制表符进行格式对齐
        count++;
        if (count >= 7) { //每输出7天换一次行
            count = count % 7;
            System.out.println();
        }
    }
    System.out.println();
}


/**
 * 初试填充
 *
 * @param startDay
 */
public static void fillSpace(int startDay) {
    for (int i = 1; i < startDay; i++) {
        System.out.print("  \t");
    }
}

/**
 * 返回指定年月的当月总天数
 *
 * @param year
 * @param month
 * @return
 */
public static int maxDayInMonth(int year, int month) {
    int max = 30;
    //判断year是否为闰年
    boolean flag = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0);
    if (month == 1 | month == 3 | month == 5 | month == 7 | month == 8 | month == 10 | month == 12) max = 31;
    else if (month == 2 & !flag) max = 28;
    else if (month == 2 & flag) max = 29;
    return max;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值