SharePoint EventReceiver AfterProperties and Date fields

I had a brief to write an EventReceiver that looked for changes to certain fields and if the changes were detected to write an entry to another list. Seems simple enough but I ran into an issue with Date fields.

In the event receiver ItemUpdating event I was checking a Date field by first extracting the current date from the properties.ListItem[“MyDateField”] then checking this against the AfterProperties[“MyDateField”]. Of course the data stored in the AfterProperties[“MyDateField”] is not a Date but is a string.

I created a DateTime object from the AfterProperties[“MyDateField”] using the Convert.ToDateTime() method. All should have been fine but it turns out the two Date values were different – even though when I was doing my testing I was not changing the MyDateField, when I tested the two values for equality the comparison was returning false.

The reason for this was that my current time zone is BST (British Summer Time) and therefore the two date values were one hour out from each other. The solution was to take the DateTime from the Convert.ToDateTime() method and then get *another* DateTime by calling the DateTime.ToUniversalTime() method. This made sure that the DateTime I got from Convert.ToDateTime(AfterProperties[“MyDateField”]) was in same time zone as the ListItem[“MyDateField”] value.

This is down to how SharePoint internally stores DateTimes, one of the CAML attributes for a Field definition pertaining to Date fields is the StorageTZ attribute, some details here:

I suspect that this is the default for a Date field.

I can only imagine the havoc this type of code problem could reek if I had written this code in the depths of a December evening (as the time zone would be GMT which is a match for UTC), got everything working, passed testing and into production. Then, come the dawn of BST on the last Sunday of March the bug would appear.

It’s often the case that we developers outside the US complain about settings being defaulted to US based settings, this is one case where the default setting is the match for the UK, luckily for me it’s summer time and I picked up the issue.

A sore one indeed.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s