0

Before marking this question as duplicate, please read further. I know this question is asked many times, but I have an addition to the general form of asking and I haven't managed finding the correct answer with respect to my use case.

I have a couple of DateTime-objects for a random time between monday and friday (no saturdays or sundays (!)).

For example:

2017-11-06 11:30:00.0000000 // Monday 6th November 2017
2017-11-07 13:30:00.0000000 // Tuesday 7th November 2017
2017-11-08 13:00:00.0000000 // Wednesday 8th November 2017
2017-11-09 15:00:00.0000000 // Thursday 9th November 2017
2017-11-10 16:00:00.0000000 // Friday 10th November 2017

I'd like to achieve the DateTime of the monday and the friday of this week at 23:59/00:00.

Question ##

So for all mentioned DateTime-objects above, I'd like to achieve the monday at starting time and the friday of :

2017-11-06 00:00:00.0000000 // Start: Monday 6th November 2017
2017-11-10 23:59:00.0000000 // Start: Friday 10th November 2017

What would be the most efficient way to solve this problem?

Ray
  • 7,940
  • 7
  • 58
  • 90
Michael D.
  • 39
  • 7

2 Answers2

0

As Dirk Schmidt answered in: Get date of first and last day of the week knowing week number

public static DateTime FirstDayOfWeek(DateTime date)
{
    DayOfWeek firstDayOfWeek= CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
    int offset = firstDayOfWeek - date.DayOfWeek;

    return date.AddDays(offset);
}

public static DateTime LastDayOfWeek(DateTime date)
{
    return FirstDayOfWeek(date).AddDays(4);
}
Hamed
  • 5,867
  • 4
  • 32
  • 56
0
private DateTime GetDay(DayOfWeek dayName, DateTime dt)
{
    if (dt.DayOfWeek == dayName)
            return dt;
        while (dt.DayOfWeek != dayName)
        {
            if (dayName == DayOfWeek.Monday)
                dt = dt.AddDays(-1);
            else
                dt = dt.AddDays(1);
        }
        return dt;
}

GetDay(DayOfWeek.Monday, Convert.ToDateTime("2017-11-06 11:30:00.0000000"));

should get you Monday of that week.

GetDay(DayOfWeek.Friday, Convert.ToDateTime("2017-11-06 11:30:00.0000000"));

should get Friday of that week.

Once you get the date of Monday and Friday, you can change the time part of the returned DateTime object appropriately.

Madhan Kumar
  • 121
  • 7