欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JAVA编写简单的日历,输入日期即可查看日历

程序员文章站 2022-06-23 23:33:41
利用LocalDate输入年月日找出当月日历 直接上代码 ......

利用localdate输入年月日找出当月日历

直接上代码

 

    package gentleman.controller;
    
    import java.time.localdate;
    import java.util.scanner;
    
    public class calendar {
        public static void main(string[] args) {
            scanner sc = new scanner(system.in);
            system.out.println("请输入要查询的日期(年-月-日用-分隔开)");
            string input = sc.nextline();
            string[] str = input.split("-");
            int year = integer.parseint(str[0]);
            int month = integer.parseint(str[1]);
            int day = integer.parseint(str[2]);
            localdate date = localdate.of(year, month, day); //将输入的数值创建一个localdate对象
            string time = year + "年" + month + "月的日历";
            date = date.minusdays(day - 1);       //不论输入的是几号,总是从第一天算起
            int value = date.getdayofweek().getvalue();   //周一到周日对应1-7
            system.out.println("       " + time);
            system.out.println();
            system.out.println(" 周一  周二 周三 周四 周五 周六  周日");  //这里空格的排序根据个人来定,我这看起来这么排顺序能对上
            for (int i = 1; i < value; i++)
                system.out.print("     ");
            while (date.getmonth().getvalue() == month) {       //如果这个月遍历完就停止
                if (date.getdayofmonth() <= 10) {                 //排版需要
                    system.out.print("  " + date.getdayofmonth() + " ");
                } else {
                    system.out.print("  " + date.getdayofmonth());
                }
                if (date.getdayofmonth() == day) {               //输入日期标注*重点
                    system.out.print("*");
                } else {
                    system.out.print(" ");
                }
                date = date.plusdays(1);                     //每次打印完就向后一天,无需管一个月是28天还是30,31天
                if (date.getdayofweek().getvalue() == 1) {
                    system.out.println();
                }
            }
        }
    }