Hey All,
What's the easiest way to determine if the last day of the year falls in the same week as the first day of the next year?
Thanks,
Hey All,
What's the easiest way to determine if the last day of the year falls in the same week as the first day of the next year?
Thanks,
var lastDay = new DateTime(2009, 12, 31);
var firstDay = new DateTime(2010, 1, 1);
bool isSameWeek = (int)lastDay.DayOfWeek < (int)firstDay.DayOfWeek;
Edit: You didn't ask this, but I think it is more interesting to calculate if two dates fall within the same week. This will also work for your question, but it also solves the problem in a much more general sense. It works by getting the calculating the start of the week for each date, then it compares if the date portions of the DateTime values are the same (just in case different times are passed in with each date).
/// <summary>
/// Determines whether two dates fall in the same week span.
/// </summary>
/// <param name="left">The left DateTime to compare.</param>
/// <param name="right">The right DateTime to compare.</param>
/// <returns>
/// </returns>
public bool IsSameWeek(DateTime left, DateTime right) {
return AreDatePartsEqual(GetStartOfWeek(left), GetStartOfWeek(right));
}
/// <summary>
/// Gets the start of week.
/// </summary>
/// <param name="date">The date.</param>
/// <returns></returns>
public DateTime GetStartOfWeek(DateTime date) {
return date.AddDays(-1 * (int)date.DayOfWeek);
}
/// <summary>
/// Compares two DateTimes using only the Date Part for equality
/// </summary>
/// <param name="left">The left DateTime to compare.</param>
/// <param name="right">The right DateTime to compare.</param>
/// <returns></returns>
public bool AreDatePartsEqual(DateTime left, DateTime right) {
return
left.Day == right.Day &&
left.Month == right.Month &&
left.Year == right.Year;
}
Just create a DateTime object for December 31st. If it doesn't fall on a Saturday, then January 1st has to be within the same week.
DayOfWeek day = new DateTime(someYear, 12, 31).DayOfWeek;
if(day < DayOfWeek.Saturday)
// January 1st must be within the same week
Edit: As Groo pointed out, the start of the week might not always be a Sunday. If it is not, then you could make it <= DayOfWeek.Saturday, or use System.Globalization.CultureInfo.DateTimeFormat.FirstDayOfWeek + 7 to find the last day of the week.
It's quite easy. If the last day is not a Sunday, then then first day of the next year must be on the same week!
Depending when you start the week, of course.