从周数c#获取日期列表

时间:2012-03-21 09:19:09

标签: c# winforms datetime

我有一个函数可以从给定日期获得当前的周数

e.g。

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

返回DateTime.Now的周数40。

所以我的问题是,也是我的问题,我需要在返回的一周内获取日期。我已经尝试了几件事,但没有人这么做。

3 个答案:

答案 0 :(得分:4)

您可以使用Time Period Library for .NET

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 );

此外,课程周支持ISO 8601周编号和自定义文化。

答案 1 :(得分:1)

您可以通过查看指定日期的工作日来查看本周的第一天和最后一天,并查找星期一:

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

答案 2 :(得分:1)

您可以使用此功能获取一周的第一个日期:

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();