Sep 04, 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.