Monday, February 28, 2011

DateTime formatting in C#

I use a custom format to show DateTime to user: "dd/MM/yyyy".

var nowString = now.ToString("dd/MM/yyyy");

The reason, I use the custom formatting, is to be not depended on user regional settings.

So, no matter what user's locale is, I expect the same format for a date.

But today I found that it does not work as I expect. On one of the target machines I got "28.02.2011" instead of expected "28/02/2011".

Why slash (/) is replaced by dot (.)? Is format string not enough explicit?

I got the answer on MSDN (RTFM!): The slash (/) is not a literal, but a pattern for the default date separator defined in DateTimeFormatInfo.DateSeparator. It has to be escaped (leading with back slash (\)), for being reproduced literally.

I fix my format string to be @"dd\/MM\/yyyy"

var nowString = now.ToString(@"dd\/MM\/yyyy");

Now it works!

No comments:

Post a Comment