Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Format returns unexpected result

I'm just wondering why this code

DateTime.Now.ToString("MM/dd/yyyy"); and String.Format("{0: MM/dd/yyyy}", DateTime.Now);

both returns 03 31 2016 instead of 03/31/2016.

like image 908
marai Avatar asked Mar 31 '16 13:03

marai


1 Answers

/ is a format specifier which is transformed to your localized date separator. Either wrap it in apostrophes or use the overload with DateTimeFormatInfo.InvariantInfo.

Console.WriteLine( DateTime.Now.ToString("MM'/'dd'/'yyyy") );  
Console.WriteLine( DateTime.Now.ToString("MM/dd/yyyy", DateTimeFormatInfo.InvariantInfo) );   

or with String.Format:

Console.WriteLine( String.Format("{0:MM'/'dd'/'yyyy}", DateTime.Now) );
Console.WriteLine( String.Format(DateTimeFormatInfo.InvariantInfo, "{0:MM/dd/yyyy}", DateTime.Now) );

You can also use CultureInfo.InvariantCulture instead of DateTimeFormatInfo.InvariantInfo.

like image 157
Tim Schmelter Avatar answered Oct 19 '22 13:10

Tim Schmelter