Datetime.ToString () C # not working as expected

From msdn, it seems that I can create my own format using the Datetime.ToString() method using M, m, d, y , etc. But when I tried one, it did not work properly, cropped below is the problem.

enter image description here

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

+7
c # datetime
source share
1 answer

It looks like the DateSeparator your CurrentCulture is - , and therefore / replace it with it.

"/" specifier of a special format is of particular importance, since I am replaced by the current culture or the culture date separator provided.

You have several options, you either escape it with single quotes (or \/ in the string literal of the string), or use a culture with / like 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); 
+19
source share

All Articles