MOSS 2007: SPListItem.GetFormattedValue for DateTime fields has a bug?
Asked Answered
C

2

6

SPListItem.GetFormattedValue seems to have a strange behavior for DateTime fields. It retrieves the DateTime value through SPListItem's indexer which according to this MSDN article returns local time. Here's a snippet from Reflector

public string GetFormattedValue(string fieldName)
{
    SPField field = this.Fields.GetField(fieldName);
    if (field != null)
    {
        return field.GetFieldValueAsHtml(this[fieldName]);
    }
    return null;
}

So it uses SPListItem's indexer to retrieve the value and than SPFields.GetFieldValueAsHtml to format the value. GetFieldValueAsHtml seems to assume the date is in UTC and convert it to local time no matter what kind it is. (Reflector shows that it uses GetFieldValueAsText which uses value.ToString() but for some reason it assumes the time to be UTC.)

The end result is that the string representation on a time field obtained trough listItem.GetFormattedValue() (at least in my case) is incorrect, being local time + (local time - UTC).

Have anybody encountered the same issue with SPListItem.GetFormattedValue() and what was your workaround?

Convexoconvex answered 10/11, 2008 at 11:13 Comment(2)
Do you want to know if anyone else has encountered it or also what they've done to get around it?Daughtry
Both :) Though there is an obvious workaround.Convexoconvex
S
7

Converting the date back to universal time before calling GetFieldValueAsHtml works just fine.

DateTime localTime = (DateTime)item["DueDate"];
// this is local time but if you do localDateTime.Kind it returns Unspecified
// treats the date as universal time.. 
// let's give it the universal time :)
DateTime universalTime = SPContext.Current.Web
    .RegionalSettings.TimeZone.LocalTimeToUTC(localTime);
string correctFormattedValue = 
    item.Fields["DueDate"].GetFieldValueAsHtml(universalTime);
Standstill answered 19/1, 2009 at 10:20 Comment(1)
Excellent answer - hope it gets flagged as correct! BTW - the same problem applies to SPFieldDateTime.GetFieldValueAsHtml(DateTime,SPWeb,SPDateFormat)Adne
M
0

I have had a recognised bug with the date conversion from UTC in SharePoint. It was fixed in SP1.

Monochromatic answered 10/11, 2008 at 19:45 Comment(5)
Hm, can't find it in the descriptions (KBs) of neither MOSS 2007 SP1 or WSS 2007 SP1.Convexoconvex
Yeah, I was surprised by the omission myself.Monochromatic
Was it this particular bug? Do you have a KB reference? I've tested WSS 3 SP1 + and its still there.Adne
I have tried to get the KB article and failed. I have since dealt with a UTC conversion bug to do with Usage Reports failing. That too does not have a KB article and is fixed in SP2.Monochromatic
This bug is not fixed in SP1 (neither WSS 3 SP1 nor MOSS 2007 SP1). Also not fixed by the Infrastructure Updates. Also not fixed as of the cumulative update from August 2010.Amigo

© 2022 - 2024 — McMap. All rights reserved.