-2

I want convert the name of days in a week (Monday,Tuesday...) into the number of days in a week (Monday=1, Tuesday=2,...)

Servy
  • 202,030
  • 26
  • 332
  • 449
RabbitBadger
  • 539
  • 7
  • 19
  • 2
    A google search for "c# convert string to dayofweek" found this [related question](http://stackoverflow.com/questions/13713366/c-datetime-dayofweek-to-string-comparison). – ryanyuyu Apr 03 '15 at 16:28
  • i would like to do it using the array method instead instead of the "if" method. – RabbitBadger Apr 03 '15 at 16:31

5 Answers5

1

You can use Enum.Parse along with the DayOfWeek enum to parse a string that has a day of the week into an integer value (which is itself just a label that wraps an integer) that corresponds to the appropriate day of the week. If you really need an integer specifically, and not an enum, you can cast that enum to an int to get its underlying value.

Servy
  • 202,030
  • 26
  • 332
  • 449
1

You could create an enum that contains all possible days, and then use Enum.Parse and cast it to an int. Though this is a bit of a "heavy hammer." Your other option is to use a switch or series of if statements to determine the number.

Pete Garafano
  • 4,863
  • 1
  • 23
  • 40
1

If you just want for days of weeks is simple in c# using

int numberDate = (int)DateTime.Now.DayOfWeek;

which will give you the number of the day

string stringDay = DateTime.Now.DayOfWeek.ToString();

which will give you the string name of the week.

Endri
  • 714
  • 13
  • 34
1

You mention using "array method". Perhaps you mean looking up the index in a constant pre-defined array/collection.

public static int ConvertDayOfWeek(string day) {
    List<string> days = new List<string>{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    return days.IndexOf(day);
}
ryanyuyu
  • 6,366
  • 10
  • 48
  • 53
1

Another idea:

If you are going to have a structure which maps string to int, simply you may use Dictionary<string,int> like this:

Dictionary<string, int> days = new Dictionary<string, int>();
days.Add("Monday",1);
days.Add("Tuesday",2);
//...

var number = days["Monday"];    //Result: 1
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116