Monday, June 29, 2009

Beware using GetFieldValueAsHtml or GetFormattedValue with DateTime fields

By Hristo Yankov

Watch out when using GetFieldValueAsHtml or GetFormattedValue with SharePoint DateTime fields! They both expect the value to be in UTC! However, SPListItem[FieldName] returns its value in Local Time zone and marks it as Unspecified.


Basically, what you have to do prior to calling one of the two methods above is make sure your time is in UTC:

DateTime localTime = (DateTime)listItem["SomeDateTime"];
DateTime universalTime = this.Web.RegionalSettings.TimeZone.LocalTimeToUTC(localTime);
string correctlyConverted = listItem["SomeDateTime"].GetFieldValueAsHtml(universalTime);
Bookmark and Share

No comments: