It’s been a while since we’ve had a reader question, so here’s one for you all. It’s not that I can’t solve this problem; it’s more that I’m wondering if there’s a more elegant solution.
The Problem: Given two dates, what’s the easiest way of determining if they fall in the same week?
Please submit your answers as a comment!
November 4th, 2008 at 12:37 am #Ben
I’ll start with a simple implementation that assumes the week begins on a Sunday.
This can be extended to work with a week beginning on a different day to Sunday:
All of these functions were unit tested and can be verified.
Do I win?
November 4th, 2008 at 1:46 am #Drew Freyling
Try the DateJs library. Its a great library with a heap of tools for all your dating needs.
November 4th, 2008 at 9:37 am #Andrew
public static bool InSameWeek(DateTime d1, DateTime d2)
{
Calendar cal = new GregorianCalendar();
int weekNo1 = cal.GetWeekOfYear(d1, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
int weekNo2 = cal.GetWeekOfYear(d2, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
return weekNo1 == weekNo2;
}
November 4th, 2008 at 9:48 am #gerrod
Thanks for the answers guys.
Ben’s answer was by far the most comprehensive and I’d lean towards that if I was making a DateTime library (which as Drew suggested, probably already exists).
Andrew’s answer however is much simpler and closer to what I need for this particular purpose.
Here’s what I came up with – essentially a cut down version of Ben’s. Note that
itemDateis the date being tested:November 4th, 2008 at 12:26 pm #Andrew
Yeah! Slow and simple wins the race. No wait, slow and special…. no wait…..
November 4th, 2008 at 10:42 pm #Ben
We should do more of these challenges as I find I always learn something new.
Thanks Andrew for pointing me towards the GregorianCalendar class.
March 18th, 2009 at 2:29 pm #Paulo Santos
I think Andrew is far from being correct. Dates in different years will result in same week.
And what happens on cases where the 1st of january is a wednesday and you compare 30/Dec with 2/Jan?
I have now the same problem, I think I ll take a look at Ben’s solution.
March 18th, 2009 at 2:32 pm #Paulo Santos
This should work
public static bool InSameWeek(DateTime d1, DateTime d2)
{
DateTime beginningOfWeekDate1 = d2.AddDays(-(int)d2.DayOfWeek);
DateTime beginningOfWeekDate2 = d2.AddDays(-(int)d2.DayOfWeek);
return beginningOfWeekDate1 == beginningOfWeekDate2;
}
Thanks Ben!
March 18th, 2009 at 2:33 pm #Paulo Santos
ops, there’s copy paste bug there.
DateTime beginningOfWeekDate1 = d1.AddDays(-(int)d1.DayOfWeek);