C# 獲取當前年份的周期及周期所在日期范圍(推薦)
最近有一個項目要用到年份周期,用于數(shù)據(jù)統(tǒng)計圖表展示使用,當中用到年份周期,以及年份周期所在的日期范圍。當初設(shè)想通過已知數(shù)據(jù)來換算年份周期,經(jīng)過搜索資料發(fā)現(xiàn)通過數(shù)據(jù)庫SQL語句來做,反而更加復雜?,F(xiàn)在改變思路通過C#后臺代碼來算出兩段日期范圍中年份周期,在依據(jù)年份周期所對應(yīng)的日期范圍進行數(shù)據(jù)庫查詢進行統(tǒng)計。需要解決以下兩個點問題,
第一點:依據(jù)日期查找所在年份的第幾周;
第二點:依據(jù)年份所在的周期計算出周期所在的日期范圍。
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication6 { class Program { static void Main(string[] args) { GregorianCalendar gc = new GregorianCalendar(); int weekOfYear = gc.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Monday); Console.WriteLine("當前第{0}周", weekOfYear); DateTime startDate, lastDate; for (int i = 1; i <= 53; i++) { GetDaysOfWeeks(DateTime.Now.Year, i, out startDate, out lastDate); Console.WriteLine("第{0}周", i); Console.WriteLine(startDate); Console.WriteLine(lastDate); } Console.ReadLine(); } public static bool GetDaysOfWeeks(int year, int index, out DateTime first, out DateTime last) { first = DateTime.MinValue; last = DateTime.MinValue; if (year < 1700 || year > 9999) { //"年份超限" return false; } if (index < 1 || index > 53) { //"周數(shù)錯誤" return false; } DateTime startDay = new DateTime(year, 1, 1); //該年第一天 DateTime endDay = new DateTime(year + 1, 1, 1).AddMilliseconds(-1); int dayOfWeek = 0; if (Convert.ToInt32(startDay.DayOfWeek.ToString("d")) > 0) dayOfWeek = Convert.ToInt32(startDay.DayOfWeek.ToString("d")); //該年第一天為星期幾 if (dayOfWeek == 0) { dayOfWeek = 7; } if (index == 1) { first = startDay.AddDays(7 - dayOfWeek - 6); if (dayOfWeek == 6) { last = first; } else { last = startDay.AddDays((7 - dayOfWeek)); } } else { first = startDay.AddDays((8 - dayOfWeek) + (index - 2) * 7); //index周的起始日期 last = first.AddDays(6); //if (last > endDay) //{ // last = endDay; //} } if (first > endDay) //startDayOfWeeks不在該年范圍內(nèi) { //"輸入周數(shù)大于本年最大周數(shù)"; return false; } return true; } } }
執(zhí)行結(jié)果
總結(jié)
以上所述是小編給大家介紹的C# 獲取當前年份的周期及周期所在日期范圍(推薦),希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
相關(guān)文章
c# socket網(wǎng)絡(luò)編程接收發(fā)送數(shù)據(jù)示例代碼
這篇文章主要介紹了c# socket網(wǎng)絡(luò)編程,server端接收,client端發(fā)送數(shù)據(jù),大家參考使用吧2013-12-12C#微信公眾號開發(fā)之用戶上下文WeixinContext和MessageContext
這篇文章介紹了C#微信公眾號開發(fā)之用戶上下文WeixinContext和MessageContext,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06基于C#?實現(xiàn)?OPC?DA?Server的問題小結(jié)
這篇文章主要介紹了基于C#?實現(xiàn)?OPC?DA?Server的相關(guān)知識,關(guān)于C#怎么編寫一個進程外的DCOM組件,這里先不做介紹了,這里主要介紹下OPC?DA?Server?的第一個接口,感興趣的朋友跟隨小編一起看看吧2024-04-04C#中的應(yīng)用程序接口介紹及實現(xiàn),密封類與密封方法
今天小編就為大家分享一篇關(guān)于C#中的應(yīng)用程序接口介紹及實現(xiàn),密封類與密封方法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-10-10