Norkevicius

June 21, 2007

Microsoft .NET Framework method ToString() is culture unsafe

Filed under: Side Notes — aurimas.norkevicius @ 12:59 pm

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.

DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

The output will be the following

2007-06-25 12:54:15.005

if current culture is “(en-EN)”

The output will be something like

2007-06-25 12.54.15.005

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

DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff",CultureInfo.InvariantCulture);

Powered by WordPress