C#學習-打印年歷,使用datetime


 1 /*編寫日期2021/8/16
 2 **開發者:市井道士
 3 **為方便同樣在此學習的各位同學,在此放出自己的答案供大家參考學習,僅供參考,隨意轉載*/
 4 using System;
 5 
 6 namespace d03
 7 {
 8 class Program
 9 {
10 static void Main(string[] args)
11 {
12 Calendar calendar = new Calendar();
13 calendar.Printdate(DateTime.Now.Year);
14 Console.WriteLine("編寫日期2021/8/16");
15 Console.WriteLine("開發者:市井道士");
16 Console.WriteLine("為方便同樣在此學習的各位同學,在此放出自己的答案供大家參考學習,僅供參考,隨意轉載");
17 Console.ReadLine();
18 }
19 }
20 class Calendar
21 {
22 /// <summary>
23 /// 輸入年月日,得到這天是星期幾
24 /// </summary>
25 /// <param name="year"></param>
26 /// <param name="month"></param>
27 /// <param name="day"></param>
28 /// <returns>星期幾</returns>
29 private static int GetWeekByDay(int year, int month, int day)
30 {
31 DateTime dt = new DateTime(year, month, day);
32 return (int)dt.DayOfWeek;
33 }
34 
35 /// <summary>
36 /// 獲取某個月的天數,輸入(int)年份,月份,返回天數(int)
37 /// </summary>
38 /// <param name="year"></param>
39 /// <param name="month"></param>
40 /// <returns>天數</returns>
41 private static int GetMonthDay(int year, int month)
42 {
43 int thismonthdays = DateTime.DaysInMonth(year, month);
44 return thismonthdays;
45 }
46 /// <summary>
47 /// 打印年歷
48 /// </summary>
49 /// <param name="year"></param>
50 public void Printdate(int year)
51 {
52 int nextlinecount;//使用一個計數器沒過一天就加1,逢7換行
53 for (int month = 1; month <= 12; month++)
54 {
55 nextlinecount = 0;//計數器每個月開始需要進行初始化
56 Console.WriteLine("{0}年{1}月",year, month);
57 Console.WriteLine("星期天\t 星期一\t 星期二\t 星期三\t 星期四\t 星期五\t 星期六\t");
58 //獲取每個月第一天是星期幾然后輸出對應次數的空格
59 for (int count=1;count <= GetWeekByDay(year,month,1);count++ ){
60 Console.Write(" \t ");
61 nextlinecount++;//計數器增加,這里的空的是上個月的日子
62 }
63 for (int day = 1; day <= GetMonthDay(year, month); day++)
64 {
65 if (nextlinecount % 7 == 0)//每次打印日期前先判斷是否為周六,逢7換行
66 Console.WriteLine();
67 Console.Write(day+"\t ");
68 nextlinecount++;
69 }
70 Console.WriteLine();
71 Console.WriteLine();
72 Console.WriteLine("=========================================================================");
73 Console.WriteLine();
74 }
75 }
76 }
77 }

 


免責聲明!

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



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