Converting DayOfWeek enum to a string repesenting the day
-
24-09-2019 - |
Question
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 0
day = "Sunday"
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 Else
day = "Apocalypse: we're all boned."
End Select
Thanks :)
Solution
A simpler way:
Dim day As String = Date.Today.DayOfWeek.ToString()
OTHER TIPS
DateTimeFormatInfo.CurrentInfo.GetDayName.
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
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.
Date.Today.DayOfWeek.ToString
will give you what you're looking for. Nice and easy.
Just in case others looked at this example. I believe it should be Case 0 for Sunday.
Case 0
day = "Sunday"