JAVA編寫簡單的日歷,輸入日期即可查看日歷


利用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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM