C#如何獲取指定周的日期範圍

1. 不允許跨年

  1) 第一週的第一天從每年的第一天開始,最後一週的最後一天爲每年的最後一天

static void Main(string[] args)
{
    DateTime first, last;
    int[] years = new int[] { 2015, 2016, 2017, 2018 };
    int[] weeks = new int[] { 1, 52, 53 };
    foreach (int y in years)
    {
        foreach (int w in weeks)
        {
            bool result = CalcWeekDay(y, w, out first, out last);
            Console.WriteLine("{0}第{1}周({2:yyyy-MM-dd} ~ {3:yyyy-MM-dd}) --{4}", y, w, first, last, result);
        }
        Console.WriteLine();
    }
}
 
public static bool CalcWeekDay(int year, int week, out DateTime first, out DateTime last)
{
    first = DateTime.MinValue;
    last = DateTime.MinValue;
    //年份超限
    if (year < 1700 || year > 9999) return false;
    //週數錯誤
    if (week < 1 || week > 53) return false;
    //指定年範圍
    DateTime start = new DateTime(year, 1, 1);
    DateTime end = new DateTime(year, 12, 31);
    int startWeekDay = (int)start.DayOfWeek;
 
    if (week == 1)
    {
        first = start;
        last = start.AddDays(6 - startWeekDay);
    }
    else
    {
        //周的起始日期
        first = start.AddDays((7 - startWeekDay) + (week - 2) * 7);
        last = first.AddDays(6);
        if (last > end)
        {
            last = end;
        }
    }
    return (first <= end);
}

2) 程序執行結果

 blob.png


2. 允許跨年

  1) 每年的尾周剩餘天數計入下一年第一週

public static bool CalcWeekDay(int year, int week, out DateTime first, out DateTime last)
{
    first = DateTime.MinValue;
    last = DateTime.MinValue;
    //年份超限
    if (year < 1700 || year > 9999) return false;
    //週數錯誤
    if (week < 1 || week > 53) return false;
    //指定年範圍
    DateTime start = new DateTime(year, 1, 1);
    DateTime end = new DateTime(year, 12, 31);
    int startWeekDay = (int)start.DayOfWeek;
    //周的起始日期
    first = start.AddDays((7 - startWeekDay) + (week - 2) * 7);
    last = first.AddDays(6);
    //結束日期跨年
    return (last <= end);
}


2) 程序執行結果
 blob.png 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章