Monthly Archives: June 2007

Microsoft .NET Framework method ToString() is culture unsafe

I’ve found out that the output of ToString() method depends on Current Culture and regional settings for that culture. So the following c#.NET code will return different strings according to the current culture.

[code lang=”c#”]DateTime.Now.ToString(“yyyy-MM-dd HH:mm:ss.fff”);[/code]

The output will be the following
[code]2007-06-25 12:54:15.005[/code]
if current culture is “(en-EN)”

The output will be something like
if current culture is “(it-IT)”

To avoid differences and to get exactly the same output as specified in format string you have to use expression
[code lang=”c#”]DateTime.Now.ToString(“yyyy-MM-dd HH:mm:ss.fff”,CultureInfo.InvariantCulture);[/code]