一年中所有星期的天数列表

时间:2016-09-27 10:04:59

标签: c#

我想要一种方法,它可以为我提供一年中所有周的日期列表。

我在此链接中找到了这个有趣的代码:Getting the list of days of the current week from DateTime.Now

Button

Jon Skeet的代码

我们能否概括一下这个案例,以便在某一年内每周治疗一次?

这是我的实际代码,灵感来自Jon Skeet的一个:

DateTime today = DateTime.Today;
int currentDayOfWeek = (int) today.DayOfWeek;
DateTime sunday = today.AddDays(-currentDayOfWeek);
DateTime monday = sunday.AddDays(1);
// If we started on Sunday, we should actually have gone *back*
// 6 days instead of forward 1...
if (currentDayOfWeek == 0)
{
    monday = monday.AddDays(-7);
}
var dates = Enumerable.Range(0, 7).Select(days => monday.AddDays(days)).ToList();

这实际上给了我实际周的一天(从星期一到星期五)的清单。

我想使用周数来访问所选周的日期列表。

1 个答案:

答案 0 :(得分:0)

public static List<DateTime> GetWeekDaysOfWeekFrom(int weekNumber)
{
    DateTime firstDayOfWeek = FirstDateOfWeekISO8601(DateTime.Today.Year, weekNumber);

    int currentDayOfWeek = (int)firstDayOfWeek.DayOfWeek;
    DateTime sunday = firstDayOfWeek.AddDays(-currentDayOfWeek);
    DateTime monday = sunday.AddDays(1);
    // If we started on Sunday, we should actually have gone *back*
    // 6 days instead of forward 1...
    if (currentDayOfWeek == 0)
    {
        monday = monday.AddDays(-7);
    }

    return Enumerable.Range(0, 7).Select(days => monday.AddDays(days)).ToList();
}

public static DateTime FirstDateOfWeekISO8601(int year, int weekOfYear)
{
    DateTime jan1 = new DateTime(year, 1, 1);
    int daysOffset = DayOfWeek.Thursday - jan1.DayOfWeek;

    DateTime firstThursday = jan1.AddDays(daysOffset);
    var cal = CultureInfo.CurrentCulture.Calendar;
    int firstWeek = cal.GetWeekOfYear(firstThursday, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

    var weekNum = weekOfYear;
    if (firstWeek <= 1)
    {
        weekNum -= 1;
    }
    var result = firstThursday.AddDays(weekNum * 7);
    return result.AddDays(-3);
}

另见Calculate date from week number