I need to get the date of the first and last day of the week knowing the week number.
I get a start date and an end date, representing the first and last day of a selected week in a given year. then I need to get the start date and end date of the same week of the previous year to do a graphical comparison of some data.
I managed to get the week number based on the given start date and end date. Now I need to get the date of the first day and last day of the same week of the previous year. How could I do this quickest ?
EDIT: This is how I got the week number:
private int GetWeekNumber(DateTime date)
{
GregorianCalendar calendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
return calendar.GetWeekOfYear(date, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
}
解决方案
You can use following two methods to calculate the week-number and the start-date of a given weeknumber according to a given year:
// this method is borrowed from http://stackoverflow.com/a/11155102/284240
public static int GetIso8601WeekOfYear(DateTime time)
{
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}
return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}
public static DateTime FirstDateOfWeek(int year, int weekOfYear, System.Globalization.CultureInfo ci)
{
DateTime jan1 = new DateTime(year, 1, 1);
int daysOffset = (int)ci.DateTimeFormat.FirstDayOfWeek - (int)jan1.DayOfWeek;
DateTime firstWeekDay = jan1.AddDays(daysOffset);
int firstWeek = ci.Calendar.GetWeekOfYear(jan1, ci.DateTimeFormat.CalendarWeekRule, ci.DateTimeFormat.FirstDayOfWeek);
if ((firstWeek <= 1 || firstWeek >= 52) && daysOffset >= -3)
{
weekOfYear -= 1;
}
return firstWeekDay.AddDays(weekOfYear * 7);
}
Then you can get both dates in the following way:
// 46
int thisWeekNumber = GetIso8601WeekOfYear(DateTime.Today);
// 11/11/2013
DateTime firstDayOfWeek= FirstDateOfWeek(2013, thisWeekNumber, CultureInfo.CurrentCulture);
// 11/12/2012
DateTime firstDayOfLastYearWeek = FirstDateOfWeek(2012, thisWeekNumber, CultureInfo.CurrentCulture);
Add 6 days to get the end of the week.