前言 :
最近遇到需要存取特定時間範圍內的資料,所以需要讓時間可以跑迴圈阿!!!
C#語言很貼心的幫我們實做迭代,所以不用自己實做foreach,但是,沒有實做日期迴圈阿!!!
沒關係,我們來練習一下
先把目標列出來 :
var today = DateTime.Now; var someday = DateTime.Now.AddDays(+10); foreach (var day in EachDay(today, someday)) { // 處理期間內邏輯... Console.WriteLine(day); }
private static IEnumerable<DateTime> EachDay(DateTime from, DateTime thru) { for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1)) yield return day; }
public static class MyDateHelper { public static IEnumerable<DateTime> EachDay(DateTime from, DateTime thru) { for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1)) yield return day; } public static IEnumerable<DateTime> EachMonth(DateTime from, DateTime thru) { for (var month = from.Date; month.Date <= thru.Date || month.Month == thru.Month; month = month.AddMonths(1)) yield return month; } public static IEnumerable<DateTime> EachDayTo(this DateTime dateFrom, DateTime dateTo) { return EachDay(dateFrom, dateTo); } public static IEnumerable<DateTime> EachMonthTo(this DateTime dateFrom, DateTime dateTo) { return EachMonth(dateFrom, dateTo); } }
ps. 有問題請歡迎告知,如果好用的話也請多給一些支持唷 (ex. 點一下廣告 : D)
沒有留言:
張貼留言