Get Friday for the given week number in C#
i need to find the date of friday for the given week number of the year for ex(week 37).
(the first friday of the 2011 is the friday that is in the week of Jan 1st. in this case the first friday is dec 31st 2010. 开发者_如何学C)
DateTime.Parse("12/31/2010").AddDays(36 * 7);
EDIT: I added a few more things, you may want a bit more, here I'm generating a list of dates, and you can then use LINQ to get what you want easily.
public void DateThing()
{
List<DateTime> dateList = new List<DateTime>();
DateTime start = DateTime.Parse("1/1/2010");
for (int i = 0; i < 1000; i++)
{
dateList.Add(start.AddDays(i));
}
var dateYouWant = GetDayOfWeekForGivenYear(DayOfWeek.Friday, 37, 2011, dateList);
}
private DateTime GetDayOfWeekForGivenYear(DayOfWeek dayOfWeek, int weekNum, int year, List<DateTime> dateList)
{
var days = dateList.Where(w => w.Year == year && w.DayOfWeek == dayOfWeek);
var day = days.FirstOrDefault(w => w.DayOfYear >= (weekNum - 1) * 7);
if (weekNum == 1)
{
return day.DayOfYear > (int)day.DayOfWeek ? day.AddDays(-7) : day;
}
else if (weekNum == 53 && day == default(DateTime))
{
return days.Last(w => w.DayOfWeek == dayOfWeek).AddDays(7);
}
return day;
}
Try something like this ...
var year = 2011;
var week = 37;
var date = new DateTime(year, 1, 1);
while (date.DayOfWeek != DayOfWeek.Friday) date.AddDays(1);
date = date.AddDays(7 * (week - 1));
This makes the assumption that week 1 of a year is the week of the first Friday. This may not always be the case ... you may want the first week of the year to be the first full week .. or the first part week ... adjust as required. Hope this helps :)
精彩评论