Check if a datetime is in same week as other datetime

16,311

Solution 1

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;
    }

Solution 2

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)
}

Solution 3

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.

Solution 4

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

Solution 5

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;
    
        }
    }
    
Share:
16,311
Lars Holdgaard
Author by

Lars Holdgaard

An entrepreneur since I was 18. Been building a lot of stuff: some successful, some not so successful Currently building the best debt collection company in the world at Likvido. In my free time (when not tinkering with code), I'm very much into crypto, traveling and being digital-nomad when it suits my lifestyle... And I blog at LarsHoldgaard.com!

Updated on July 06, 2022

Comments

  • Lars Holdgaard
    Lars Holdgaard almost 2 years

    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?

  • DxCK
    DxCK over 8 years
    How about 31/12/2015 and 01/01/2016 that occur in the same week but different years?
  • Electric Sheep
    Electric Sheep over 7 years
    This will only work if you want the week to start from Sunday.
  • Simon Hänisch
    Simon Hänisch about 7 years
    @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.
  • Shoejep
    Shoejep over 5 years
    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;
  • Arve Systad
    Arve Systad almost 5 years
    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.
  • SHS
    SHS over 4 years
    @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
  • david-so
    david-so about 3 years
    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;
  • Peter Thaus
    Peter Thaus almost 3 years
    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!
  • Yiorgos
    Yiorgos about 2 years
    You only want to compare dates up to day precision (not hours etc), so the final line should be: return d1.Date == d2.Date;