27

When i write a date in C# by using

DateTime.Now.ToString("yyyy/MM/dd")

then it returns 2010-09-10, but I need 2010/09/10. How do I make it output slashes?

1
  • I'm not sure what's being asked here. Are you trying to convert a date with dashes into a date with slashes? Commented Sep 10, 2010 at 11:08

3 Answers 3

37

Use

DateTime.Now.ToString("yyyy'/'MM'/'dd");

/ - the date separator. It will be replaced according current culture. So you need enclose it with char literal delimiter (') to use it like char.

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#dateSeparator

2
  • +1: Didn't know that you could override it like that! Commented Sep 10, 2010 at 11:15
  • You mean the char literal delimiter, not string.
    – ProfK
    Commented Mar 11, 2017 at 5:57
31

Specify a culture. Your current culture uses - for the separators, and that's what ToString defaults to (your current culture), unless you override it.

You can try this:

DateTime.Now.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture)

but perhaps it would be better if you specified a different culture, for instance if you want the US culture:

DateTime.Now.ToString("yyyy/MM/dd", CultureInfo.GetCultureInfo("en-US"))

Both of the above will give you / as a separator.

2
  • What namespace is CultureInfo in? Commented Jan 13, 2022 at 16:36
  • @aaron-franke System.Globalization Commented Dec 20, 2023 at 14:16
9

Another way is to specify the slashes as character literals:

DateTime.Now.ToString("yyyy'/'MM'/'dd");
"2010/09/10"