C# date formatting is losing slash separators

C#DatetimeString Formatting

C# Problem Overview


If I do this in C#:

Console.WriteLine(DateTime.Now.ToString("ddd M/dd/yy"));

I would expect output like this:

Wed 6/15/11

But it actually outputs this:

Wed 6 15 11

Why are the slashes disappearing? Is there a way to prevent this and have the date outputted in the expected format?

C# Solutions


Solution 1 - C#

Console.WriteLine(DateTime.Now.ToString("ddd M/dd/yy", CultureInfo.InvariantCulture));
            Console.ReadLine();

try the above

Solution 2 - C#

You could also use

Console.WriteLine(dateTime.ToString("ddd M'/'dd'/'yy"));

That's a possible solution if you're not using the invariant culture as mentioned in other answers here.

Solution 3 - C#

The default behavior of the "/" (slash) in a format argument is to use the current's culture date separator.

To force the "/" (slash), you must precede it with a "" (backslash).

Ex.: "yyyy\\/MM\\/dd" will always display a date like "2015/07/02" independent of the current culture in use.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJon TackaburyView Question on Stackoverflow
Solution 1 - C#DavidView Answer on Stackoverflow
Solution 2 - C#NorbertView Answer on Stackoverflow
Solution 3 - C#BaRtErView Answer on Stackoverflow