Given a string with the day of the week, we return an integer
Is there a way to have something like:
string day = "Sunday";
int num = getDayOfWeek(day); //returns 0
I understand that we could do something like this and I wanted to reverse:
int num = 0;
//returns "Sunday"
return System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.DayNames[(int)num];
The easiest way is to implement a dictionary that does what I ask, but I'm wondering if there is something in C#
DateTime
that already does this for me.
EDIT:
As Jon Skeet noted, it would be ideal if the answer supported different cultural days (eg "Sunday" in English, "Segunda" in Portuguese).
+3
source to share
2 answers
You can do the following:
string myDay = "Tuesday";
int dayNumber = ((int)Enum.Parse(typeof(DayOfWeek), myDay)); // dayNumber = 2
Every day of the week is mapped to the following number:
- Sunday = 0
- Monday = 1
- Tuesday = 2
- Wednesday = 3
- Thursday = 4
- Friday = 5
- Saturday = 6
+3
source to share