Sep 4, 2011

Convert Integer to Day of Week in .NET

If you are working on DayOfWeek and saving it as integer in database then you need to convert integer to day of week(Sunday,Monday…) again to show data on page. This article explains how you can do this easily.
The DayOfWeek enumeration represents the day of the week in calendars that have seven days per week.


Enum.GetName Method retrieves the name of the constant in the specified enumeration that has the specified value and we can get DayOfWeek easily using it. See following:

 Response.Write(Enum.GetName(typeof(DayOfWeek),5));

Output:

Friday
————————————-

If you have to convert CSV integers to CSV day of week, see following sample to convert “1,2,5” using LINQ.

var t = string.Join(",",
                 from g in "1,2,5".Split(new char[] { ',' })
                 select Enum.GetName(typeof(DayOfWeek), Convert.ToInt32(g)));
        Response.Write(t);

Output:

Monday,Tuesday,Friday
—————————————
Hope, It helps.

2 comments

    1. Hey jra
      I know it’s been 2 whole years since your comment and I don’t event know if you’ll read this, but I had the same question and didn’t find any solutions online, so I wanted to share the method I used.
      The way I managed to get the DayOfWeek value was to make a List containing all of the weekdays, and then use the List index to get the DayOfWeek value, like this:

      List weekDays = new List { DayOfWeek.Sunday, DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday, DayOfWeek.Saturday };

      And then you get a value from the list like this:

      DayOfWeek day = weekDays[int];

Leave a Reply

Your email address will not be published. Required fields are marked *