Monday, July 5, 2010

Adjusting date time values in SharePoint 2010

Technorati Tags: ,,

It is well known that SharePoint stores date time values in GMT(Greenwich Mean Time). This is done in order for SharePoint to adjust date time values according to site or user regional setting preferences. On a recent project I had to determine how to adjust date time values returned from search results, for example the “Last Modified” value for a document. The value is returned in GMT time and users complained it was not the same value as what was showing in the document library in SharePoint.  Below is a picture of list of time zones SharePoint displays to choose from when setting the regional settings for a Site. Notice some time zones are listed with a negative number of hours compared to the GMT time and others are listed with a positive number.

SharePoint exposes the SPTimeZoneInformation class to enable your code to make the same regional setting adjustments as the UI. Below is code showing you how to use this class, along with the logic to adjust for daylight savings time. The strange thing is that the Bias value is opposite of the value displayed in the time zone list. For example, central time is listed as being 6 hours behind GMT, however the value for the Bias which is in minutes is a positive value. Conversely, the Bias value for Amsterdam which is listed as an hour ahead of GMT is a negative value. So you must reverse the sign of the value before adjusting the date time value.


           int timeZoneBiasMinutes = 0;

           DateTime newVal;

           DateTime tmpVal = DateTime.Now;

           if (SPContext.Current != null && SPContext.Current.Web != null)
               SPTimeZoneInformation info =
               timeZoneBiasMinutes = info.Bias;

               DateTime now = DateTime.Now;
               SPSystemTime daylightDate = info.DaylightDate;

               if(now.Month >= daylightDate.Month)
                   if(now.Day >= daylightDate.Day)
                       timeZoneBiasMinutes += info.DaylightBias;

               if (timeZoneBiasMinutes > 0)
                  minAdjustment = -timeZoneBiasMinutes;
                  minAdjustment = Math.Abs(timeZoneBiasMinutes);

               newVal = ((DateTime)tmpVal).AddMinutes(minAdjustment);

No comments:

Post a Comment