Tuesday, November 3, 2015

SharePoint GetFieldValueAsHtml or GetFormattedValue with DateTime fields Show One Day Earlier

Question:

What am I doing incorrectly here?  I simply want to get the date value from an SPFieldDateTime, which I thought was working until I looked into it closer:

1) I input 10/01/2008 into the field
2) in the code, it consistently reads 09/30/08
(tested with mulitple dates, it always removes a day from the inputted value)

the kicker is, however, that the field contains the correct date!!!
see below, the object is the same throughout:

?field.GetFieldValue (listItem(field.Id))
"10/1/2008" {String}
String: "10/1/2008"
?field.GetFieldValueAsText (listItem(field.Id))
"9/30/2008"
?field.GetFieldValueForEdit (listItem(field.Id))
"9/30/2008"
?field.GetFieldValueAsHtml (listItem(field.Id))
"9/30/2008"
?listitem(field.Id).ToString
"10/1/2008 12:00:00 AM"

Answer:

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);

0 comments:

Post a Comment