利用LocalDate输入年月日找出当月日历
直接上代码
1 import java.time.LocalDate;
2 import java.util.Scanner;
3
4 public class Calendar{
5 public static void main(String[] args) {
6 Scanner sc = new Scanner(System.in);
7 System.out.println("请输入要查询的日期(年-月-日用-分隔开)");
8 String input = sc.nextLine();
9 String[] str = input.split("-");
10 int year = Integer.parseInt(str[0]);
11 int month = Integer.parseInt(str[1]);
12 int day = Integer.parseInt(str[2]);
13 LocalDate date = LocalDate.of(year, month, day); //将输入的数值创建一个LocalDate对象
14 String time = year + "年" + month + "月的日历";
15 date = date.minusDays(day - 1); //不论输入的是几号,总是从第一天算起
16 int value = date.getDayOfWeek().getValue(); //周一到周日对应1-7
17 System.out.println(" " + time);
18 System.out.println();
19 System.out.println(" 周一 周二 周三 周四 周五 周六 周日"); //这里空格的排序根据个人来定,我这看起来这么排顺序能对上
20 for (int i = 1; i < value; i++)
21 System.out.print(" ");
22 while (date.getMonth().getValue() == month) { //如果这个月遍历完就停止
23 if (date.getDayOfMonth() < 10) { //排版需要
24 System.out.print(" " + date.getDayOfMonth() + " ");
25 }
26 else if (date.getDayOfMonth()>=10){
27 System.out.print(" " + date.getDayOfMonth());
28 }
29 if (date.getDayOfMonth() == day) { //输入日期标注*重点
30 System.out.print("*");
31 } else {
32 System.out.print(" ");
33 }
34 date = date.plusDays(1); //每次打印完就向后一天,无需管一个月是28天还是30,31天
35 if (date.getDayOfWeek().getValue() == 1) {
36 System.out.println();
37 }
38 }
39 }
40 }