15

Let's say I have a list of dates in a table. Now I want to find all rows, which is in the same week as the date provided as an argument.

Let's say I have a table with:

  • 2014-09-11
  • 2014-09-12
  • 2014-09-15

And I give this function the argument 2014-09-09, it has to look from monday->sunday, and realize that 09-11 and 09-12 is part of the week, but not 09-15.

How on earth to solve this?

I have thought on making a check on year, month and weeknumber, but you cannot guarantee that month is the same...

So how do you solve a problem like this?

Lars Holdgaard
  • 9,496
  • 26
  • 102
  • 182
  • Parse it into a Date-Time object and extract the week of year from that? – SiKing Sep 11 '14 at 19:06
  • see here: http://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week – thumbmunkeys Sep 11 '14 at 19:06
  • Related: [How can I determine the week number of a certain date?](http://stackoverflow.com/questions/7918593/how-can-i-determine-the-week-number-of-a-certain-date) – crashmstr Sep 11 '14 at 19:07
  • 1
    [http://msdn.microsoft.com/en-us/library/system.globalization.calendar.getweekofyear.aspx](http://msdn.microsoft.com/en-us/library/system.globalization.calendar.getweekofyear.aspx) – Sagar Pilkhwal Sep 11 '14 at 19:08
  • Depending on your locale, the week could start on a different day: Sunday and Monday are common. – Sergey Kalinichenko Sep 11 '14 at 19:16

9 Answers9

23

DxCk's comment is valid. This solution will work even if the first or last week of the year cross two different years:

Check that the first day of the week for both dates fall on the same day. Here is the code:

    private bool DatesAreInTheSameWeek(DateTime date1, DateTime date2)
    {
        var cal = System.Globalization.DateTimeFormatInfo.CurrentInfo.Calendar;
        var d1 = date1.Date.AddDays(-1 * (int)cal.GetDayOfWeek(date1));
        var d2 = date2.Date.AddDays(-1 * (int)cal.GetDayOfWeek(date2));

        return d1 == d2;
    }
Sparrow
  • 2,548
  • 1
  • 24
  • 28
  • 1
    This will only work if you want the week to start from Sunday. – Electric Sheep Sep 16 '16 at 13:20
  • 1
    @OllieP you can fix that easily by subtracting `1` from the day of week: `date1.AddDays(-((int)date1.DayOfWeek-1))`. This should be the accepted answer imo. – Simon Hänisch May 11 '17 at 05:01
  • I'd rather just create a tiny helper method that returns appropriate numbers for weekdays where I'm from than "magically subtracting" from DayOfWeek, as this requires people to know that the built in Enum starts on Sunday. – Arve Systad Jun 28 '19 at 08:01
  • @Sparrow, your solution does not do the job properly in the countries, where weeks start from Monday. Try the above code with 1/11/2020 and 6/11/2020 – SHS Jan 24 '20 at 07:45
  • You only want to compare dates up to day precision (not hours etc), so the final line should be: return d1.Date == d2.Date; – Yiorgos Mar 07 '22 at 21:59
  • doesn't work for a french calendar e.g. 03/10/2022 and 9/10/2022 – Aminos Oct 19 '22 at 13:51
10

why not?

bool AreFallingInSameWeek(DateTime date1, DateTime date2)
{
    return date1.AddDays(-(int)date1.DayOfWeek) == date2.AddDays(-(int)date2.DayOfWeek);
}

if you want to use any day other than Sunday as start of the week

bool AreFallingInSameWeek(DateTime date1, DateTime date2, DayOfWeek weekStartsOn)
{
    return date1.AddDays(-GetOffsetedDayofWeek(date1.DayOfWeek, (int)weekStartsOn)) == date2.AddDays(-GetOffsetedDayofWeek(date2.DayOfWeek, (int)weekStartsOn));
}

int GetOffsetedDayofWeek(DayOfWeek dayOfWeek, int offsetBy)
{
    return (((int)dayOfWeek - offsetBy + 7) % 7)
}
kodebot
  • 1,718
  • 1
  • 22
  • 29
  • 1
    You should be wary of using these in .Net core as the milliseconds on the DateTime will cause almost always a return value of false, i.e. AreFallingInSameWeek(DateTime.Now, DateTime.Now, DayOfWeek.Monday) will return false, but you can solve this by adding .Date, like this: date1.AddDays(-GetOffsetedDayofWeek(date1.DayOfWeek, (int)weekStartsOn)).Date == date2.AddDays(-GetOffsetedDayofWeek(date2.DayOfWeek, (int)weekStartsOn)).Date; – Shoejep Oct 04 '18 at 09:28
  • For the first of the two solutions presented, you get false because it is also comparing the time. Just add `.Date` at the end of both values to compare just the day as follow: `return date1.AddDays(-(int)date1.DayOfWeek).Date == date2.AddDays(-(int)date2.DayOfWeek).Date;` – david-so Mar 26 '21 at 12:30
4

Check the DateTime.Year and Calendar.GetWeekOfYear(DateTime, ...). No need to check for the month.

EDIT: This is wrong but I can't delete it. See @Sparrow's answer below.

Robert Levy
  • 28,747
  • 6
  • 62
  • 94
  • 10
    How about 31/12/2015 and 01/01/2016 that occur in the same week but different years? – DxCK Dec 21 '15 at 14:21
3

Use: public virtual int GetWeekOfYear(DateTime time,CalendarWeekRule rule,DayOfWeek firstDayOfWeek) of Calendar class

Sagar Pilkhwal
  • 3,998
  • 2
  • 25
  • 77
2

My requirement was to find DOBs falling on the current week. Hope this helps with your doubt. Basically the idea behind this code is as follows:

  1. Change the DOB to current year birthday (eg; 24-02-1988 to 24-02-2018(current year).
  2. Add a year, if the brithday week contains both dec and jan
  3. Get the first day of today's week.
  4. Get last day of today's week.
  5. check if the current year birthday falls between first day and last day of today's week.

    private bool DatesAreInTheSameWeek(DateTime birthday)
    {
        if (birthday == DateTime.MinValue)
        {
            return false;
        }
        else
        {
            var birtdayWithCurrentYear = new DateTime(DateTime.Today.Year, birthday.Month, birthday.Day);
            if (birthday.Month == 1 && DateTime.Today.Month != 1)
            {
                birtdayWithCurrentYear = birtdayWithCurrentYear.AddYears(1);
            }
            DateTime firstDayInWeek = DateTime.Today.Date;
            while (firstDayInWeek.DayOfWeek != CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
                firstDayInWeek = firstDayInWeek.AddDays(-1);var lastDayInWeek = firstDayInWeek.AddDays(7);
    
            return birtdayWithCurrentYear < lastDayInWeek && birtdayWithCurrentYear >= firstDayInWeek;
    
        }
    }
    
Rahul Jacob
  • 19
  • 1
  • 5
1

Since the accepted answer contains error as @DxCK mentioned in comment, here is my solution for this:

public static class DateExtensions
{
    private static void Swap<T>(ref T one, ref T two)
    {
        var temp = one;
        one = two;
        two = temp;
    }

    public static bool IsFromSameWeek(this DateTime first, DateTime second, DayOfWeek firstDayOfWeek = DayOfWeek.Monday)
    {
        // sort dates
        if (first > second)
        {
            Swap(ref first, ref second);
        }

        var daysDiff = (second - first).TotalDays;
        if (daysDiff >= 7)
        {
            return false;
        }

        const int TotalDaysInWeek = 7;
        var adjustedDayOfWeekFirst = (int)first.DayOfWeek + (first.DayOfWeek < firstDayOfWeek ? TotalDaysInWeek : 0);
        var adjustedDayOfWeekSecond = (int)second.DayOfWeek + (second.DayOfWeek < firstDayOfWeek ? TotalDaysInWeek : 0);

        return adjustedDayOfWeekSecond >= adjustedDayOfWeekFirst;
    }
}

Also here is link to another correct solution with slightly different approach.

Community
  • 1
  • 1
steavy
  • 1,483
  • 6
  • 19
  • 42
1

Find start and end dates for the first date's week. Then check if the second date is between those two.

   public static bool DateInsideOneWeek(DateTime date1, DateTime date2)
    {
        DayOfWeek firstDayOfWeek = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
        DateTime startDateOfWeek = date1.Date;
        while(startDateOfWeek.DayOfWeek != firstWeekDay)
        { startDateOfWeek = startDateOfWeek.AddDays(-1d); }
        DateTime endDateOfWeek = startDateOfWeek.AddDays(6d);
        return date2 >= startDateOfWeek && date2 <= endDateOfWeek;
    }
  • I tried this and had some trouble with the date as the date to check contained a time also. So I added startDateOfWeek.AddHours(-startDateOfWeek.Hour); to remove the hours, same with minutes and then the endDateOfWeek = startDateOfWeek.AddDays(7d); so I have the date starting on midnight and ending on midnight one week later. This worked fine for me. Thanks! – Peter Thaus Jun 27 '21 at 16:15
0

If you don't want to use the Calendar class you can use this function:

public static int WeekOfYear(DateTime dt)
{
    int startDays = 0;
    // first day of the year
    DateTime firstJanuary = new DateTime(dt.Year, 1, 1);

    if (firstJanuary.DayOfWeek == DayOfWeek.Tuesday)
    {
        startDays = 1;
    } 
    else if (firstJanuary.DayOfWeek == DayOfWeek.Wednesday)
    {
        startDays = 2;
    }
    else if (firstJanuary.DayOfWeek == DayOfWeek.Thursday)
    {
        startDays = 3;
    }
    else if (firstJanuary.DayOfWeek == DayOfWeek.Friday)
    {
        startDays = 4;
    }
    else if (firstJanuary.DayOfWeek == DayOfWeek.Saturday)
    {
        startDays = 5;
    }
    else if (firstJanuary.DayOfWeek == DayOfWeek.Sunday)
    {
        startDays = 6;
    }

    if (DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek == DayOfWeek.Sunday)
    {
        startDays++;
        startDays = startDays % 7;
    }

    return ((dt.DayOfYear + startDays - 1) / 7) + 1;
}
daniel
  • 132
  • 7
0

Accepted answer doesn't work for a french calendar and when the dates are 03/10/2022 and 09/10/2022.

This worked for me :

    public static partial class DateTimeExtensions
    {
        public static DateTime FirstDayOfWeek(this DateTime dt)
        {
            var culture = System.Threading.Thread.CurrentThread.CurrentCulture;
            var diff = dt.DayOfWeek - culture.DateTimeFormat.FirstDayOfWeek;

            if (diff < 0)
            {
                diff += 7;
            }

            return dt.AddDays(-diff).Date;
        }

        public static DateTime LastDayOfWeek(this DateTime dt) =>
            dt.FirstDayOfWeek().AddDays(6);

        public static DateTime FirstDayOfMonth(this DateTime dt) =>
            new DateTime(dt.Year, dt.Month, 1);

        public static DateTime LastDayOfMonth(this DateTime dt) =>
            dt.FirstDayOfMonth().AddMonths(1).AddDays(-1);

        public static DateTime FirstDayOfNextMonth(this DateTime dt) =>
            dt.FirstDayOfMonth().AddMonths(1);

        public static int GetWeeekNumber(this DateTime dt)
        {
            CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture;
            Calendar myCal = culture.Calendar;

            // Gets the DTFI properties required by GetWeekOfYear.
            CalendarWeekRule myCWR = culture.DateTimeFormat.CalendarWeekRule;
            DayOfWeek myFirstDOW = culture.DateTimeFormat.FirstDayOfWeek;

            return myCal.GetWeekOfYear(dt, myCWR, myFirstDOW);
        }

        public static bool IsInTheSameWeek(this DateTime date1, DateTime date2)
        {
            return date1.GetWeeekNumber() == date2.GetWeeekNumber();
        }
    }

Usage :

item.Week.IsInTheSameWeek(Week)
Aminos
  • 754
  • 1
  • 20
  • 40