0

I have to check that my specific date day is between two string days or equals to them For instance:

var startDay = "Saturday";
var endDay = "Tuesday";
DateTime myDate = DateTime.Now;
if(myDate.DayofWeek >= startDay && myDate.DayofWeek <= endDay){
//some code here...
}
Slan
  • 545
  • 2
  • 6
  • 18
  • 1
    Duplicate, really? That one is about converting a string into the Enum which is certainly one thing OP needs to do, but the question here is about figuring out if a date is between two weekdays. – juunas Jun 28 '16 at 06:12

2 Answers2

3

You could use the DayOfWeek enum.

if(myDate.DayOfWeek >= DayOfWeek.Tuesday 
   && myDate.DayOfWeek <= DayOfWeek.Saturday)
{
    // This would catch the days from Tuesday to Saturday
}

If you want to catch the days from Saturday to Tuesday you have to change a bit your code.

    if(myDate.DayOfWeek >= DayOfWeek.Saturday 
    || myDate.DayOfWeek <= DayOfWeek.Tuesday)
{
    // This would catch the days from Tuesday to Saturday
}

If your startDate and endDate are changing. Then you need to parse the first and do a few extra checks.

DayOfWeek startDayOfWeek;
DayOfWeek endDayOfWeek;
if (!Enum.TryParse(startDay, out startDayOfWeek))
{
    // Something wrong happened and you have to handle it.
}
if (!Enum.TryParse(endDay, out endDayOfWeek))
{
    // Something wrong happened and you have to handle it.
}
if (
       ((int)startDayOfWeek < (int)endDayOfWeek
         && myDate.DayOfWeek >= startDayOfWeek
         && myDate.DayOfWeek <= endDayOfWeek)
    || ((int)startDayOfWeek > (int)endDayOfWeek
         && (myDate.DayOfWeek >= startDayOfWeek
             || myDate.DayOfWeek <= endDayOfWeek))
   )
{

}
Christos
  • 53,228
  • 8
  • 76
  • 108
2

You can parse those strings to a DayOfWeek enum:

var startDay = "Saturday";
var endDay = "Tuesday";
DayOfWeek startDayOfWeek, endDayOfWeek;
if (!Enum.TryParse(startDay, out startDayOfWeek))
   // error handlnig
if (!Enum.TryParse(endDay, out endDayOfWeek))
   // error handlnig
DateTime myDate = DateTime.Now;
if(myDate.DayofWeek >= startDayOfWeek && myDate.DayofWeek <= endDayOfWeek){
    //some code here...
}

But that gives another problem: the values of DayOfWeek go from sunday (0) to saturday (6). And depending on what you define as start of your week or what between means, you might need to adjust the values.

So here is a suggestion:

int startDayAsInt = (int)startDayOfWeek; // the parsed value from above
int endDayAsInt = (int)endDayOfWeek;
int myDateAsInt = (int)myDate.DayOfWeek;

if (endDayAsInt < startDayAsInt) endDayAsInt += 7;
if (myDateAsInt < startDayAsInt) myDateAsInt += 7;
if (myDateAsInt >= startDayAsInt && myDateAsInt <= endDayAsInt)
    // do something

This should work for all combinations as it projects days into the "next" week if they are before the start day.

René Vogt
  • 43,056
  • 14
  • 77
  • 99