Thursday, November 8, 2012

SPListItem.GetFormattedValue Returns Wrong Date, One Day Prior

Recently I was working with some lists that had a lot of Managed Metadata columns.  I was developing a custom webpart that would display the contents of these fields for the user.  Of course I went straight to the SPListItem.GetFormattedValue method.  It works like a charm on just about every field you throw at it, except for dates!

In my example I was getting a date that was 1 day prior, IE: my field held 1/2/2012 and the method would return 1/1/2012!  Argh!!!  This would also happen with SPField.GetFieldValue and its counterparts.

The problem is that the method is expecting a UTC time but the value is in a local timezone, so you've got to do some sort of conversion here.

Here was my solution:

 string  myString;
if  (listItem.Fields["THISCOLUMN"].Type == SPFieldType.DateTime)
 SPFieldDateTime  dtField = (SPFieldDateTime )listItem.Fields[column];
    DateTime  dTime = Convert.ToDateTime(listItem["THISCOLUMN"].ToString());
    if  (dtField.DisplayFormat == SPDateTimeFieldFormatType.DateOnly)
        myString = dTime.ToShortDateString();
        myString = dTime.ToString();
    myString = listItem.GetFormattedValue("THISCOLUMN");

Basically, we test the field in the SPListItem and check if its a SPFieldType.DateTime.  If so, we cast it to an SPFieldDateTime.  Then we create a DateTime object and convert the field value.  Then we can test the SPFieldDateTime object to determine its display type, either DateOnly or DateTime.  If its DateOnly then we use the ToShortDateString() method, if not just ToString().  If its not a DateTime object at all, we just use the plain old GetFormattedValue() method.

A little bit of work, but it fit my bill.


No comments:

Post a Comment