3

In my local machine System short Date setting is of format "M/d/yyyy". In my C# code i can convert DateTime to "dd/MM/yyyy" or "dd-MM-yyyy" format using

//1
var date=string.Format("{0:dd/MM/yyyy}", DateTime.Now) //output is:05/09/2017
//2
var date=string.Format("{0:dd-MM-yyyy}", DateTime.Now) //output is:05-09-2017

But if i change my system date settings of short date to "yyyy-MM-dd" or simply any date format having "-" as separator instead of "/" i'm unable to convert date to other formats like

//3
var date=string.Format("{0:dd-MM-yyyy}", DateTime.Now) //output is:05-09-2017
//4
var date=string.Format("{0:dd/MM/yyyy}", DateTime.Now) //output is still :05-09-2017

In the above code even i have changed separator to "/" it's still giving "-" in the output.How can i output 4th one to "05/09/2017".

DavidG
  • 113,891
  • 12
  • 217
  • 223
Ein2012
  • 1,103
  • 1
  • 13
  • 33
  • You can try ToString format: DateTime.Now.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture); – Viliam Sep 05 '17 at 09:50

1 Answers1

6

The / character is a special formatting character for DateTime which says "use the specified/current locale's date separator".

If you want to force it to use / you have to escape the character by surrounding it with single quotes:

var date=string.Format("{0:dd'/'MM'/'yyyy}", DateTime.Now)

Alteratively, you can escape it with the \ character:

var date=string.Format("{0:dd\\/MM\\/yyyy}", DateTime.Now)

(But I find the first approach to be slightly more readable.)

Finally, you can also use double-quotes to escape it, but that's even less readable:

var date = string.Format("{0:dd\"/\"MM\"/\"yyyy}", DateTime.Now);

Alternatively (as Jon points out) you can override the culture to use one that uses / as a separator:

var date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now);
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276