BitterCoder's Wiki

Edit

Daylight savings not working

In the SPGridView, unlike normal views for a list it displays date fields without applying the current users regional settings i.e. timezone and culture.

I created a replacement column for dates which fixes this, applying the culture of the current user/web - this also inadvertently fixes the timezone issues, and allows for additional customization of the date's formatting via the "DateFormat" property or improving your custom essay quality.

Edit

The Code



[SharePointPermission(SecurityAction.InheritanceDemand, ObjectModel = true), AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal), SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true), AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)] public class LocalizedDateSPBoundField : SPBoundField { private readonly CultureInfo _culture; private string _dateFormat = "g"; public LocalizedDateSPBoundField() { SPRegionalSettings regionalSettings = SPContext.Current.Web.CurrentUser.RegionalSettings ?? SPContext.Current.Web.RegionalSettings; if (regionalSettings != null) { _culture = new CultureInfo((int) regionalSettings.LocaleId); } else { _culture = CultureInfo.CurrentUICulture; } }

public string DateFormat { get { return _dateFormat; } set { if (string.IsNullOrEmpty(value)) throw new ArgumentNullException("value"); _dateFormat = value; } }

protected override void ChildControlDataBinding(Control childControl, object dataItem, MemberDescriptor dataFieldPropertyDescriptor) { string value = GetPropertyValue(dataItem, dataFieldPropertyDescriptor.Name);

Label label = (Label) childControl;

DateTime date; if (DateTime.TryParse(value, out date)) { label.Text = date.ToString(DateFormat, _culture); } else { label.Text = value; } }

protected override Control GetChildControlInstance() { return new Label(); } }



Edit

Usage

You can now replace this:

<SharePoint:SPBoundField DataField="DueDate" HeaderText="Due Date" SortExpression="DueDate" />


With this:

<MyControls:LocalizedDateSPBoundField DataField="DueDate" HeaderText="Due Date" SortExpression="DueDate"/>


Or, for say a short date-only display, using the "d" format string:

<MyControls:LocalizedDateSPBoundField DateFormat="d" DataField="DueDate" HeaderText="Due Date" SortExpression="DueDate"/>


Edit

Additional thoughts

I suspect that this may not "fix" the daylight savings in some scenarios, in which case you could probably use the additional methods which can be accessed on the timezone within the SPRegionalSettings i.e. SPContext.Current.Web.CurrentUser.RegionalSettings.TimeZone.

  • DateTime SPTimeZone.UTCToLocalTime(DateTime)
  • DateTime SPTimeZone.LocalTimeToUTC(DateTime)
  • Custom essays

ScrewTurn Wiki version 2.0.2. Some of the icons created by FamFamFam.