SharePoint Tip of the Day : Be careful when working with date & time in SharePoint !


Microsoft SharePoint stores date and time values in Coordinated Universal Time (UTC, but also named GMT or Zulu) format, and almost all date and time values that are returned by members of the object model are … in UTC format.

Unfortunately, there is one big exception and that’s probably the case you’ll be using the most : the list column values that are obtained through the indexer for the SPListItem class are already formatted in the local time for the site so if you’re working on current context list item and fetch a datetime field like so SPContext.Current.ListItem[“Your-DateTime-Field”] you’ll retrieve a DateTime object according the the specified time zone in the regional settings (and taking into account the “lovely” summer / winter time).

Other special case is whenever you want to display a date time value in your page layout, instead of using the generic field value :

<SharePointWebControls:FieldValue FieldName=”Modified” runat=”server” />

You should use the specific date time field value <SharePointWebControls:DateTimeField FieldName=”Modified” runat=”server” /> which will return the value according to the time zone of the current SPWeb.

As a final reminder, whenever you’re doing a CAML query and you’re working with date you can specify the property DatesInUTC to grab them as they are stored and I heavily suggest you to work with Offset (positive or negative) from Today <Today Offset=”10″ />
 or generate your Zulu “TZ date” (eg : 2012-05-24T16:32:00Z) based on a specific UTC time (and not the server current time). So instead of working with a DateTime.Now, rely on DateTime.UtcNow to avoid unexpected behaviour.

Hope it helps.

Advertisements

4 thoughts on “SharePoint Tip of the Day : Be careful when working with date & time in SharePoint !

  1. Your tip on DateTimeField was very helpful!
    For SharePoint 2013, using ‘SharePointWebControls’ didn’t work but this code did the trick for me:

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