JAVA - 利用calendar类做出日历

目录

效果

输入年份、月份,输出日历。

QQ截图20150425170215.png

代码

!!!java
package com.software.oop;

import java.util.Calendar;
import java.util.Scanner;

public final class MyCalendar {

    private Calendar calendar;
    //field:域  对应  字段(属性)
    public MyCalendar(){
        //对象实例化,抽象类不能用new调用,只能调用抽象类的子类或者查找参考文档中能调用的。
        calendar = Calendar.getInstance();
    }

    /*
     *1.一个月的第一天是星期几
     *2.判断是否为闰年
     *3.求一个月的天数
     */
    //判断是否为闰年
    public boolean isLeapYear(int year){
        if (year % 400 == 0||(year % 4 == 0 && year %100 != 0))
            return true;
        else 
            return false;
    }
    //判断月份天数
    public int getDays(int year,int month) {
        if(month == 1||month == 3 || month == 5 ||month == 7 || month == 8 ||month == 10 || month == 12)
            return 31;
        if(isLeapYear(year) && month ==2)
            return 29;
        if(!isLeapYear(year) && month == 2)
            return 28;
        if(month == 4||month == 6||month == 9||month == 11)
            return 30;
        return 0;
    }

    public void display() {
        int firstDay;//定义临时变量
        int flag = 0;//控制换行
        //输入
        int year,month;
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入年份:");
        year = scanner.nextInt();
        System.out.println("请输入月份(1-12):");
        month = scanner.nextInt();
        //定位到输入的年月份
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month-1);

        System.out.print("\t------------");
        System.out.println(calendar.get(Calendar.YEAR)+"年"+(calendar.get(Calendar.MONTH)+1)+"月-------------");
        System.out.println("\n日\t一\t二\t三\t四\t五\t六");
        //定位到本月1日
        calendar.set(Calendar.DATE, 1);
        //获取到本月1日是周几
        firstDay = calendar.get(Calendar.DAY_OF_WEEK);
        //System.out.println(firstDay);
        //输出本月1日前的空白
        for (int i = 1; i < firstDay; i++) {
            System.out.print("\t");
            flag++;
        }
        //输出日与日之间的空格
        for (int i = 1; i <= getDays(year, month); i++) {
            System.out.print(i);
            System.out.print("\t");
            flag++;
            //输出换行
            if (flag % 7 == 0) {
                System.out.println("\n");
            }
        }
        /*calendar.set(Calendar.YEAR, 1995);//set修改
        System.out.print("现在是"+calendar.get(Calendar.YEAR)+"年");
        System.out.print(calendar.get(Calendar.MONTH)+1+"月");//月份从0开始,所以加1
        System.out.print(calendar.get(Calendar.DATE)+"日");
        System.out.print(calendar.get(Calendar.HOUR_OF_DAY)+"时");
        System.out.print(calendar.get(Calendar.MINUTE)+"分");
        System.out.print(calendar.get(Calendar.SECOND)+"秒");*/
    }

    public static void main(String[] args) {
        MyCalendar myCalendar = new MyCalendar();
        myCalendar.display();
    }

}

标签: java

声明:本博客如无特殊说明皆为原创,转载请注明来源:JAVA - 利用calendar类做出日历谢谢!

相关文章