DateTime formatting for fr-CA

I just stumbled across a nice little hidden “feature” in the .NET framework.  If you’re running on a machine that has the CurrentCulture set to fr-CA the default DateTimeFormatInfo.CurrentInfo.ShortDatePattern is dd-MM-yyyy.  On my current project we wanted to allow the end user to override that value with their own format when a date is displayed on the screen.  The easy way to do this is to do something like DateTime.Now.ToString(“dd/MM/yyyy”).  Unfortunately the result from that will appear as 16-09-2010 still.  As far as I can tell (and there is very little backing this up), this is by design.  I’m not sure why at all.  If the CurrentCulture is set to en-CA both the formats of dd/MM/yyyy and dd-MM-yyyy will cause ToString() to output a value that you would expect, but as soon as you trip over to fr-CA the rules seem to change.

If you’re running into this there is a relatively simple solution.  DateTime.Now.ToString(“dd\/MM\/yyyy”) will output 16/06/2010 as you’d expect.

The more localization that I’m doing on this application, the more I’m finding nice hidden gems of inconsistency like this.

posted @ Thursday, September 16, 2010 11:33 AM

Print

Comments on this entry:

# re: DateTime formatting for fr-CA

Left by Vlad Dudas at 9/16/2010 4:00 PM
Gravatar
This is due to the fact that "/" is a special character in date time formatting.

The behaviour you're described is documented in msdn.microsoft.com/en-us/library/8kb3ddd4.aspx.

This allows you not to worry about the date separator characters.

You could alternately set DateTimeFormatInfo.CurrentInfo.DateSeparator = "/"

# re: DateTime formatting for fr-CA

Left by WilliamH at 9/16/2010 6:35 PM
Gravatar
What about using the InvariantCulture format provider in those instances?

DateTime.Today.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)

# re: DateTime formatting for fr-CA

Left by Donald at 9/20/2010 9:57 AM
Gravatar
Good call on this. Tried it this morning and it seems to have worked the trick. Thanks William.

# re: DateTime formatting for fr-CA

Left by Lucas at 10/1/2010 8:05 AM
Gravatar
"there is very little backing this up", here's your backup ;)

From msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

The "/" represents the culture's date separator, which can be "/", "-", ".", or others. The "\" is an escape charater. By using "\/" you are using an actual slash instead of the culture's date separator. Similarly, if you wanted a "d" and not the day of the month, you would use "\d".

# re: DateTime formatting for fr-CA

Left by Nero at 2/9/2011 6:18 PM
Gravatar
Great, tried this trick and worked.
Comments have been closed on this topic.