0 Comments

I experienced a strange behaviour with the DateTime class and formatting today. For some reason this error only occurs when you format a DateTime in certain cultures like Italian. The error is not present in English, Danish and most other cultures.

It happens when you use the DateTime.ToString and DateTime.ParseExact methods. When you write the following:

String date = DateTime.Now.ToString("yyyy-MM-dd HH:mm")

You would expect the date variable to be formatted like so 2008-01-05 11:30. In Italian it doesn’t. Instead it replaces the colon with a period which produces this 2008-01-05 11.30. This might be correctly formatted for the Italian culture, but I explicitly wrote I wanted the colon delimiter in the format string. However, there is a workaround.

All you need is to change the format string into a less obvious one. The following produces the right colon delimited date and time string:

String date = DateTime.Now.ToString("yyyy-MM-dd HH\\:mm")

Strangely enough, you have to escape the colon with two backslashes for it to work. This trick seems to work in all cultures.