tags:

views:

182

answers:

3

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,

+4  A: 
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;
}
Bob
+4  A: 

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.

Brandon
I think maybe he's meaning same week number. Or else it would just be too simple (:) Still simple though)
sindre j
+1 for simplicity
JustLoren
And if your week starts with Monday, you might want to use `if(day <= DayOfWeek.Saturday)`.
Groo
+5  A: 

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.

Philippe
Using domain knowledge to solve a problem? Upvote!
Dean J
What if the last day is a Saturday? Doesn't that mean that the first day of the next year (Sunday) is not in the same week? (Assumes Sunday is the first day of the week)
Chris Dunaway