9

From msdn it seems like I can create my own format with Datetime.ToString() method by using M, m, d, y etc. But when I tried one it didn't worked as expected, snipped below is the issue.

enter image description here

I was expecting 7/29/2015 but received 7-29-2015 !!! why?

yogi
  • 19,175
  • 13
  • 62
  • 92
  • 2
    Because [`/` is the date separator configured on your system](https://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#dateSeparator). Use `'/'` for a literal slash. – Frédéric Hamidi Jul 29 '15 at 12:39
  • @Adil The difference is '-' and '/' – Alex Neves Jul 29 '15 at 12:44
  • possible duplicate of [How to format a date with slashes in C#](http://stackoverflow.com/questions/3684033/how-to-format-a-date-with-slashes-in-c-sharp) – Dzyann Jul 29 '15 at 13:44

1 Answers1

22

Looks like your DateSeparator of your CurrentCulture is - and that's why / character replace itself to it.

"/" custom format specifier has a special meaning as replace me with current culture or supplied culture date separator.

You have a few options, you either escape it with single quotes (or \/ in a verbatim string literal) or use a culture that has / as a DateSeparator like InvariantCulture.

string s = DateTime.Now.ToString("M'/'d'/'yyyy");
string s = DateTime.Now.ToString(@"M\/d\/yyyy");
string s = DateTime.Now.ToString("M/d/yyyy", CultureInfo.InvariantCulture);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • ohhhkkkk... thanks mate.. will accept when allowed soon.. :) – yogi Jul 29 '15 at 12:45
  • @yogi No. You can play around. A `/` in your string means "use the date separator of the format provider in question". However, `'/'` or `\/` means "include a literal slash". So either `"M'/'d'/'yyyy"` or `@"M\/d\/yyyy"` will be fine. – Jeppe Stig Nielsen Jul 29 '15 at 12:45