Search code examples
c#dayofweek

ToString("ddd") does not work for DayofWeek abbreviated to 3 characters


I am trying to simply get the 3 letter acronym for the day of the week.

Monday = MON
Tuesday = TUE
and so on.

I tried this but I get an error.

string wsDoW = DateTime.Today.DayOfWeek.ToString("ddd");

The only way around it for me, is this...

string wsDoW = DateTime.Today.DayOfWeek.ToString().ToUpper().Substring(0,3);

The error is ...

Format String can be only "G", "g", "X", "x", "F", "f", "D" or "d".

What's going on?


Solution

  • Remove the DayOfWeek portion and your format specifier will work just fine.

    string wsDoW = DateTime.Today.ToString("ddd");
    

    This is due to the difference in the ToString() implementation between System.DateTime and System.DayOfWeek.

    The ToString implementation in the DateTime class ends up here, where it's testing for far more format specifiers.

    The ToString implementation being called on DayOfWeek is in the Enum class, where it only checks for a few format specifiers, and throws an exception if it isn't one of those.