Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a datetime is in same week as other datetime

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?

like image 404
Lars Holdgaard Avatar asked Sep 11 '14 19:09

Lars Holdgaard


People also ask

What does DateTime compare do?

Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance.

How to compare DateTime format in C#?

Compare() method in C# is used for comparison of two DateTime instances. It returns an integer value, <0 − If date1 is earlier than date2. 0 − If date1 is the same as date2.

How to use date time C#?

To work with date and time in C#, create an object of the DateTime struct using the new keyword. The following creates a DateTime object with the default value. The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight). The maximum value can be December 31, 9999 11:59:59 P.M.

What does DateTime now return in C#?

The Now property returns a DateTime value that represents the current date and time on the local computer.


2 Answers

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)
}
like image 58
kodebot Avatar answered Oct 13 '22 03:10

kodebot


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;
    }
like image 43
Sparrow Avatar answered Oct 13 '22 02:10

Sparrow