Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DayOfWeek get the next DayOfWeek(Monday,Tuesday...Sunday)

Tags:

c#

dayofweek

Is there a way to summarize this code into 1-2 lines?

My goal is to return, for example, I have a DayOfWeek which is Monday, I want to get the day after that (Tuesday) or n days after that.

         switch (_RESETDAY)
        {
            case DayOfWeek.Monday:
                _STARTDAY = DayOfWeek.Tuesday;
                break;
            case DayOfWeek.Tuesday:
                _STARTDAY = DayOfWeek.Wednesday;
                break;
            case DayOfWeek.Wednesday:
                _STARTDAY = DayOfWeek.Thursday;
                break;
            case DayOfWeek.Thursday:
                _STARTDAY = DayOfWeek.Friday;
                break;
            case DayOfWeek.Friday:
                _STARTDAY = DayOfWeek.Saturday;
                break;
            case DayOfWeek.Saturday:
                _STARTDAY = DayOfWeek.Sunday;
                break;
            case DayOfWeek.Sunday:
                _STARTDAY = DayOfWeek.Monday;
                break;
            default:
                _STARTDAY = DayOfWeek.Tuesday;
                break;
        }
like image 940
Katherine Avatar asked Sep 28 '15 15:09

Katherine


People also ask

What is DayOfWeek in c#?

Use DateTime. DayOfWeek property to display the current day of week. DayOfWeek wk = DateTime. Today.

Which is the day of the week?

In English, the names are Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday, then returning to Monday. Such a week may be called a planetary week.

How do you find the day of the week in a string?

String[] days = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; Display the day name.


2 Answers

This is just an int enumeration, ranging from Sunday (0) to Saturday (6), as per MSDN:

The DayOfWeek enumeration represents the day of the week in calendars that have seven days per week. The value of the constants in this 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 simple math should do it:

DayOfWeek nextDay = (DayOfWeek)(((int)_RESETDAY + 1) % 7);

Replace + 1 with + n if that's what you need.

like image 162
Andrei Avatar answered Sep 30 '22 14:09

Andrei


Yes.

(DayOfWeek)((int)(_RESETDAY+1)%7)
like image 42
Ian Newson Avatar answered Sep 30 '22 15:09

Ian Newson