DateTime Localization in ASP .NET

You’ve got an ASP .NET app and you need to display a date. Normally that just involves the old DateTime.ToShortDateString() or DateTime.ToString(“d”) and you continue coding on your merry little way. But what happens when your users are from different countries and expect different date formats.  Between Australia, USA and Japan there are 3 different date formats.

Then answer? The HttpRequest’s UserLanguages. This string array basically maps to the following languages that you can setup in your browser:

Now for the code:


CultureInfo culture = Request.UserLanguages != null
? CultureInfo.CreateSpecificCulture(Request.UserLanguages[0])
: CultureInfo.CurrentCulture;
myLabel.Text = DateTimeOffset.Now.ToLocalTime().ToString("d", culture);
Don’t forget to check if the UserLanguages is not null since you can remove all the values from the list if you like.
Also, if you are looking at ways to do this client side, ScottGu’s Blog has a nice post on a new jquery plugin for this.

* Update *
Just realised that you don’t need to any of this if you use the following in your web.config:

<globalization uiCulture="auto" culture="auto" />
Posted in .Net, Asp.Net, C# by Drew at June 18th, 2010.

Leave a Reply