Java日历制作

Java中如何实现一个简单的日历@TOC

整体思路

要实现的功能为:在控制台输入相对应的日期的字符串,然后打印出当月的日历;

  1. 用到Scanner类,用于获取控制台输入的日期信息;
  2. 用到SimpleDateFormat类,用于设置日期格式,并将字符串形式的日期解析为Date形式;
  3. 此时Date类的对象代表的日期为我们输入的日期;
  4. 用Date对象初始化Calendar对象,然后通过Calendar对象的方法获得当月最大天数calendar.getActuralMaxmum(Calendar.DAY_OF_MONTH),当天是当月的第几天calendar.get(Calendar.DAY_OF_MONTH),当月第一天是星期几calendar.get(DAY_OF_WEEK);

代码如下:
public class mycalendartest2 {
public static void main(String args[]){

    new mycalendartest2().myCalendar();
}

public void myCalendar(){
    int maxday = 0;
    int firstday = 0;
    int currentday = 0;

    System.out.println("请输入一个日期: 格式为:2016-08-09");
    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();

    try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = sdf.parse(str);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d1);

        maxday = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        currentday = calendar.get(Calendar.DAY_OF_MONTH);
        firstday = calendar.get(Calendar.DAY_OF_WEEK) - 1;


    }
    catch(ParseException e){
        e.printStackTrace();
    }

    System.out.println("日\t一\t二\t三\t四\t五\t六\t\n");
    for(int i = 0; i < firstday; i++){
        System.out.print("\t");
    }
    for(int j = 1; j <= maxday; j++){
        if(j == currentday){
            System.out.print("#" + "\t");
            if ((j + firstday) % 7 == 0) {
                System.out.print("\n");
            }
        }
        else {
            System.out.print(j + "\t");
            if ((j + firstday) % 7 == 0) {
                System.out.print("\n");
            }
        }
    }
}

}

输入1994-04-17结果为:
请输入一个日期: 格式为:2016-08-09
1994-04-17
日 一 二 三 四 五 六
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 # 18 19 20 21
22 23 24 25 26 27 28
29 30
Process finished with exit code 0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值