When adding a SharePoint list item the one field type that has given me most problems is the SPDateTimeField:First there is the question of entering the date in a format that SharePoint accepts. Then there is the problem of getting the time zone right.
Fortunately, neither of the two problems are actually hard to solve – Microsoft has tried to make life easy for us by supplying the tools we need to solve them quietly and efficiently.
Setting a valid date
SharePoint accepts date entered in ISO8601 format. So all we need to do is to enter the date in the following format:
You could of course do a
but that is a bit cumbersome, and you are bound to sometimes get the formatting wrong. Luckily, Microsoft has provided us with the following method, which is found in the Microsoft.SharePoint.Utilities namespace of the Microsoft.SharePoint assembly:
This creates a string with the correct format. There is also the opposite method that creates a DateTime object:
Unfortunately, if you use the above on a random DateTime object to set the date and time of a list item, you will probably see that the time part is offset by a number of hours. This can happen even if you get the DateTime value directly from the same list item that you are inserting it into.
Getting the time part correct
The problem with the time part offset is of course a matter of time zones. There are several places we can fiddle with the time zone, including on the web application and the individual site. But there is a (again Microsoft-provided) simpler way:
This creates a DateTime object with the correct time zone. If you insert this object in the CreateISO… method above, you will get a string that SharePoint interpretes as having the correct time zone. As before, the opposite method also exists:
Setting date and time is always tricky, due to the many different formats and time zones. In the SharePoint object model we have methods that lets us handle these issues in a standardized manner. These methods are available both in the full object model, and in the limited sandboxed object model.