Date Format Checking & SharePoint

When coding some date-related functionality within a WebPart, there can be circumstances in which the “date format” is incorrectly applied, according to local settings.

Within Australia – we operate as “dd/mm/yyyy” – not the American format of “mm/dd/yyyy”.

My code is :

DateTime dt;

if (DateTime.TryParse ( dateValue, out dt ) )

… do something

But, I was finding that it was still checking using a “US Date Format” – and so values such as 28/02/2008 were failing.    (failing – 28th month)

Globalization is always a tricky one, and have heard comments about SharePoint not acknowledging the local culture setting.

Regardless, there is a way to FORCE the DateTime check to use the normal date time within Australia (dd/mm/yyyy).

Just need to include some additional paramters with the “TryParse” function :

(don’t forget to add reference to System.Globalization )

DateTime dt;

if (DateTime.TryParse( dateValue, new CultureInfo(“en-AU”), DateTimeStyles.NoCurrentDateDefault, out dt ) )

That seemed to work for me.   I can now have a date range of “20/02/2008 – 28/02/2008” without any validation errors.

And – a value of “02/20/2008” will show an error.    (dd/mm/yyyy)

NB.  This is simply C# / .NET code – doesn’t have to be within a WebPart/SharePoint – just another way of using “DateTime.TryParse”.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s