Thursday, March 19, 2009

Getting the correct month, no matter the country

Recently I posted about localisation and today need to have a page work out a given month's index value (ie: 1-12) from a string. Because I'm developing the code in the UK and hosting it in the US, the localisation was mucking about with the handling of the DateTime.Parse() interpretation of the date string. I needed the code to handle the parsing as if it was in the UK, no matter where it's hosted.

In short, the answer is from a MSDN article: http://msdn.microsoft.com/en-us/library/bz9tc508.aspx

There are two methods, both easy, to use. The first is in the page's page tag (at the top), where the 'GB' forces things like datetime to use Great Britain formatting:

<%@ Page ... Culture="en-GB" ... %>

The second is in the web.config, again it's the GB:

<system.web>
<globalization uiCulture="en" culture="en-GB" />
...
</system.web>

Now, my code will render properly:

DateTime.Parse("01/" + Int32.Parse(month) + "/2009").ToString("MMMM")

Don't ask why I'm doing that, it's just necessary, is all.

I'm preferring the web.config approach, but it's perfectly valid for the page - just be sure to remember which pages use the setting. Obviously, this can all be set dynamically, but you'll have to read the MSDN pages for how to do that - this is just a reminder for myself and anyone who might run across my pages.

No comments:

Post a Comment