C#判斷某年某月共有多少個週末,分別是哪幾天
阿新 • • 發佈:2019-01-01
注:本文中的週末指的是週六和週日雙休
本程式碼用的是基姆拉爾森公式來判斷某年某月某天是否為週末,關於這個公式,百度百科上有詳細介紹,這裡再贅述一下:
基姆拉爾森計算公式:W= (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400) mod 7,在公式中d表示日期中的日數,m表示月份數,y表示年數。
注意:在公式中有個與其他公式不同的地方:把一月和二月看成是上一年的十三月和十四月,例:如果是2004-1-10則換算成:2003-13-10來代入公式計算。
下面貼程式碼:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication19 { class Program { static void Main(string[] args) { int Y = 2011; // 記錄年份,可以改動,也可以通過控制元件輸入 int M = 6; // 記錄月份,可以改動,也可以通過控制元件輸入 List<int> Weekend_list = new List<int>(); // 用來記錄月份中雙休日的編號(從1開始) int Month_number = DateTime.DaysInMonth(Y, M); // 用來記錄一個月中的天數 for (int i = 1; i <= Month_number;i++ ) { if (Whether_Weekend(Y, M, i)) { Weekend_list.Add(i); } } Console.WriteLine("{0}年{1}月共有{2}個雙休日,分佈如下:/r",Y,M,Weekend_list.Count); foreach (int item in Weekend_list) { Console.WriteLine("{0}號/r", item); } Console.ReadLine(); } public static bool Whether_Weekend(int y ,int m ,int d) { if (m == 1 || m == 2) { m += 12; y--; } int week = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7; // 基姆拉爾森公式 if (week == 5 || week == 6) { return true; } else { return false; } } } }