java 时间类使用

运行结果

package com.study;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class CalendarDemo {

    public static void main(String[] args) {

        //创建当前日历对象
        GregorianCalendar now = new GregorianCalendar();
        //从当前日期对象中取出时间日期对象
        Date date = now.getTime();
        System.out.println(date.toString());
        //重新将时间对象设置到日期对象中
        now.setTime(date);
        //从当前日期对象中取出当前月份、日期
        int today = now.get(Calendar.DAY_OF_MONTH);
        int month = now.get(Calendar.MONTH);
        //设置日期为本月开始日期
        now.set(Calendar.DAY_OF_MONTH, 1);
        //获取本月开始日期在一周中的编号
        int week = now.get(Calendar.DAY_OF_WEEK);
        //打印日历头并换行
        System.out.println("星期日 星期一 星期二 星期三 星期四 星期五 星期六");
        //设置当前月中第一天的开始位置
        for(int i = Calendar.SUNDAY;i<week;i++){
            System.out.print("               ");
            //按规格循环打印当前月的日期数字
            while(now.get(Calendar.MONTH)==month){
                //取出当前日期
                int day = now.get(Calendar.DAY_OF_MONTH);
                //设置日期数字小于10与不小于10两种情况打印规格
                if(day<10){
                    //设置当前日期的表示形式
                    if(day == today){
                        System.out.print("<"+day+"> ");
                    }else {
                        System.out.print("  "+day+"  ");
                    }
                }else {
                    //设置当前日期的表示形式
                    if(day == today){
                        System.out.print("<"+day+"> ");
                    }else {
                        System.out.print(" "+day+"  ");
                    }
                }

                //设置什么时候换行
                if(week == Calendar.SATURDAY){
                    System.out.println();
                }

                //设置日期与星期几为下一天
                now.add(Calendar.DAY_OF_MONTH, 1);
                week = now.get(Calendar.DAY_OF_WEEK);
            }

        }

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值