Skip to main content

XrmToolBox: AutoNumberUpdater - new StateCode filter

How to correctly display a SPFieldCalculated with datatype DateTime

In this blog I want to talk about my recent experiences with displaying values from a SPFieldCalculated field with datatype "DateTime" in another Web control (asp textbox or label).

My first approach was this:

// Get calculated due date field values and set them in the textboxes
SPFieldCalculated cf3Due = (SPFieldCalculated)SPContext.Current.ListItem.Fields["Due date"];

DueDateField.Text = cf3Due.GetFieldValueAsText(SPContext.Current.ListItem["Due_x0020_date"]);

Later I figured out that using the first approach will not correctly apply timezone and region settings to the current datetime values.

My next approach solved my issue with displaying the right datetime in the right timezone. But it took me several hours to find out this freaking solution.

System.Globalization.CultureInfo ci = null;
SPRegionalSettings regSettings = null;
var user = SPContext.Current.Web.CurrentUser;
// Always perform a Null-Check on SPUser.RegionalSettings
if (user.RegionalSettings != null)
{
    regSettings = user.RegionalSettings;
    ci = System.Globalization.CultureInfo.GetCultureInfo((int)user.RegionalSettings.LocaleId);
}
else
{
    // User didn't set a time zone, so use the one from the Web
    regSettings = SPContext.Current.Web.RegionalSettings;
    ci = System.Globalization.CultureInfo.GetCultureInfo((int)SPContext.Current.Web.RegionalSettings.LocaleId);
}

string[] calculatedFieldParts = ((string)SPContext.Current.ListItem["Due_x0020_date"]).Split(';');

//strip leading # from value
string fieldValue = calculatedFieldParts[1].Remove(0, 1);

DueDateField.Text = Microsoft.SharePoint.Utilities.SPUtility.FormatDate(SPContext.Current.Web, regSettings.TimeZone.LocalTimeToUTC(System.Convert.ToDateTime(fieldValue)), Microsoft.SharePoint.Utilities.SPDateFormat.DateTime);
I don't know if this is actually an ideal approach, but it seems to work well in my in our customer's enviroment. If you know a better way to do this please leave a quick comment on this topic.

Comments