从第c#周获取日期列表

本文关键字:列表 取日期 周获 从第 | 更新日期: 2023-09-27 18:28:42

我有一个函数,可以从给定日期中获取当前周数

例如

GregorianCalendar cal = new GregorianCalendar(GregorianCalendarTypes.Localized);
return cal.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

返回DateTime.Now的第40周。

所以我的问题是,也是我的问题,我需要得到返回周的日期。我试过几种方法,但都没有奏效。

从第c#周获取日期列表

您可以使用.NET:的时间段库的类Week

Week week = new Week( new DateTime( 2012, 03, 21 ) );
Console.WriteLine( "week #: ", week.WeekOfYear );
Console.WriteLine( "week first day: ", week.FirstDayOfWeek );
Console.WriteLine( "week last day: ", week.LastDayOfWeek );

此外,Week类支持ISO8601周编号和自定义区域性。

您可以使用此函数来获取一周中的第一个日期:

public static DateTime FirstDateOfWeek(int year, int weekOfYear)
{
    DateTime jan1 = new DateTime(year, 1, 1);
    int daysOffset = Convert.ToInt32(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek) - Convert.ToInt32(jan1.DayOfWeek);
    DateTime firstWeekDay = jan1.AddDays(daysOffset);
    System.Globalization.CultureInfo curCulture = System.Globalization.CultureInfo.CurrentCulture;
    int firstWeek = curCulture.Calendar.GetWeekOfYear(jan1, curCulture.DateTimeFormat.CalendarWeekRule, curCulture.DateTimeFormat.FirstDayOfWeek);
    if (firstWeek <= 1) {
        weekOfYear -= 1;
    }
    return firstWeekDay.AddDays(weekOfYear * 7);
}

然后你可以通过以下方式获取本周的所有日期:

var firstDate = FirstDateOfWeek(2012, 40);
var allWeekDays = new List<DateTime>();
allWeekDays.Add(firstDate);
var currentDate = firstDate;
for(int d = 1; d < 7; d++)
{
    currentDate=currentDate.AddDays(1);
    allWeekDays.Add(currentDate);
}

或者在一行中:

var week = Enumerable.Range(0,7).Select(d => firstDate.AddDays(d)).ToList();

只需查看给定日期的工作日,就可以获得一周中的第一天和最后一天,并查找星期一:

DateTime firstDay = date.Date;
while (firstDay.DayOfWeek != DayOfWeek.Monday) {
  firstDay = date.AddDays(-1);
}
DateTime lastDay = firstDay.AddDays(6);