(JavaSE 学习记录) Calendar日历类、日历表的打印

Galendar类

Galendar类为抽象类,通常使用其子类GregorianCalendar类来实现,其主要用来对日期进行相关展示和计算。

对象的创建初始化:可直接通过构造器输入年月日、时分秒或调用setTime()方法丢入Date类对象来创建。

Calendar calendar = new GregorianCalendar(2000,12,9,6,20,24);
calendar.setTime(new Date());//Date类转化为日历类
Date date = calendar.getTime();//日历类转化为Date类

相关查询和设置:使用set、get方法

int year = calendar.get(Calendar.YEAR);//几几年
int month = calendar.get(Calendar.MONTH);//0~11,几月
int day01 = calendar.get(Calendar.DAY_OF_MONTH);//几号
int day02 = calendar.get(Calendar.DATE);//与DAY_OF_MONTH同义
int day03 = calendar.get(Calendar.DAY_OF_WEEK);//1~7,1为周日

calendar.set(Calendar.YEAR,2000);//几几年
calendar.set(Calendar.MONTH,1);//0~11,几月
calendar.set(Calendar.DAY_OF_MONTH,1);//几号
calendar.set(Calendar.DATE,1);//与DAY_OF_MONTH同义
calendar.set(Calendar.DAY_OF_WEEK,1);//1~7,1为周日

对Calendar类进行日期、时间的加减:使用add()

        calendar.add(Calendar.DATE,-1);//减去一天
        calendar.add(Calendar.DATE,1);//加上一天

综合运用打印日历表:

public class CalendarTest {
    public static void main(String[] args) throws ParseException {
        System.out.println("请输入要查找的日期,格式为1999-12-31");
        //Calendar类、Date类、String类之间的转换
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        Date date = sd.parse(str);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);

        int day = calendar.get(Calendar.DAY_OF_MONTH);
        //本月最大为几号
        int max = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.set(Calendar.DAY_OF_MONTH,1);
        int first = calendar.get(Calendar.DAY_OF_WEEK);//1号为周几
        System.out.println("日 \t一 \t二 \t三 \t四 \t五 \t六");
        //根据一号为周几,让一号能正确显示到周几下
        for(int i = 0;i<first-1;i++){
            System.out.print("\t\t");
        }

        int counter = first-1;	//记录为周几,根据习惯让1对应周一
        for(int i =1;i<=max;i++){
        	//这里仅仅只是为了美观,小于9时补零,并将指定日期标记出来
            if(i<=9){
                if(i==day){
                    System.out.print("0" + i + "*\t");
                }else {
                    System.out.print("0" + i + "\t");
                }
            }else{
                if(i==day){
                    System.out.print(i + "*\t");
                }else {
                    System.out.print(i + "\t");
                }
            }

            counter++;
            //周日时换行
            if(counter%7==0){
                System.out.println();
            }
        }


    }
}

结果展示:
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值