Greycrow
Greycrow

Reputation: 1633

DateTime DayOfWeek Comparison

Id like to Compare a date to see if it is before Saturday like so:

        //Check if Saturday YET
        if (MYWorkDay.DayOfWeek < DateTime.DayOfWeek.Saturday)
            IGottaWork();
        else
            Party();

There seems to be no way to do this.

Is there a way?

Thanks in advance

Upvotes: 9

Views: 20392

Answers (5)

pure_eval
pure_eval

Reputation: 61

From MSDN:

The value of the constants in the DayOfWeek enumeration ranges from DayOfWeek.Sunday to DayOfWeek.Saturday. If cast to an integer, its value ranges from zero (which indicates DayOfWeek.Sunday) to six (which indicates DayOfWeek.Saturday).

So you can also use greater than and less than operators for your calculation.

//Check if Saturday YET
if (MYWorkDay.DayOfWeek < DayOfWeek.Saturday && MYWorkDay.DayOfWeek > DayOfWeek.Sunday)
    IGottaWork();
else
    Party();

Upvotes: 4

wsanville
wsanville

Reputation: 37506

If you would rather do comparisons rather than checking a list, you could also do this:

if ((MYWorkDay.DayOfWeek.CompareTo(DayOfWeek.Sunday) > 0) && (MYWorkDay.DayOfWeek.CompareTo(DayOfWeek.Saturday) < 0))
{
      IGottaWork();
}
else
{
      Party();
}

Upvotes: 1

mtmk
mtmk

Reputation: 6316

DayOfWeek is an enum starting with Sunday as 0 and Saturday as the last element hence 6 in integer terms. Think of that when comparing.

Upvotes: 1

Andrew Hare
Andrew Hare

Reputation: 351466

Why not this?

    if (MYWorkDay.DayOfWeek != DayOfWeek.Saturday
          && MYWorkDay.DayOfWeek != DayOfWeek.Sunday) 
    {
        IGottaWork();
    }
    else
        Party();

Or even better:

List<DayOfWeek> partyDays = new List<DayOfWeek> {
    DayOfWeek.Saturday, DayOfWeek.Sunday
};

if (partyDays.Contains(MYWorkDay.DayOfWeek))
    Party();
else
    IGottaWork();

Upvotes: 15

John Feminella
John Feminella

Reputation: 311436

Try this:

if (new [] {DayOfWeek.Saturday, DayOfWeek.Sunday}.Contains(d.DayOfWeek)) {
  // party :D
} else {
  // work  D:
}

Upvotes: 0

Related Questions