views:

380

answers:

5

I was wondering if there was a way to directly convert the integer DayOfWeek returns into a string representing the day like Monday, Tuesday etc.

Sample code:

MessageBox.Show(Date.Today.DayOfWeek)

This will return 6 (as of today). Is there a way to directly convert this into Saturday, for example? I don't really care what it really converts it into, but I want to do away with my Select Case:

            Select Case Date.Today.DayOfWeek
                Case 1
                    day = "Monday"
                Case 2
                    day = "Tuesday"
                Case 3
                    day = "Wednesday"
                Case 4
                    day = "Thursday"
                Case 5
                    day = "Friday"
                Case 6
                    day = "Saturday"
                Case 7
                    day = "Sunday"
                Case Else
                    day = "Apocalypse: we're all boned."
            End Select

Thanks :)

A: 

DateTime.DayOfWeek doesn't return an integer - it returns an enum of type DayOfWeek. I'd expect that to be converted into the name automatically, but maybe this is a VB subtlety; maybe something to do with using Date instead of DateTime? Try this:

MessageBox.Show(DateTime.Today.DayOfWeek.ToString())

This won't be culture-sensitive though - it will always just display the name of enum value, in English. If that's not good for you, use Zyphrax or itowlson's solution.

Jon Skeet
This will return the invariant (US English) name; fine for debugging or storing in a database or whatever, but if he's displaying it he should be using something that localises the string.
itowlson
@itowlson: I was just editing to say something similar, but less specifically. Not *every* UI needs to be localised, IMO. There are plenty of apps which will only ever be in one language (think internal apps for non-international companies). If that language is English, that makes life even easier.
Jon Skeet
Thanks. And this code is just to reference some TextBoxes in my form in a timetable order. The actual data going to be displayed is coming from a database :)
James
A: 

There's a DateTime format for that: dddd

Dim date1 As Date = #08/29/2008 7:27:15PM#
date1.ToString("dddd", CultureInfo.CreateSpecificCulture("en-US"))

With the CultureInfo you can get it in a specific language (it's optional)

For more info: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#ddddSpecifier

Zyphrax
+3  A: 

A simpler way:

Dim day As String = Date.Today.DayOfWeek.ToString()
Rubens Farias
Cheers, worked. Should of checked the `ToString()` method :)
James
+1  A: 

DateTimeFormatInfo.CurrentInfo.GetDayName.

itowlson
A: 

Date.Today.DayOfWeek.ToString will give you what you're looking for. Nice and easy.

Dennis Palmer