Home > Sharepoint > Custom Sharepoint DateTimeField webcontrol with DateFormat property

Custom Sharepoint DateTimeField webcontrol with DateFormat property

September 18th, 2010

I was adding a Sharepoint datetime control to my page layout and I wanted to control the way the date was displayed. I found out that the Sharepoint control can’r do this. So I wrote a simple control for this. See source code below

using System;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;

namespace Webcontrols
{
   public class CustomDateTimeControl : DateTimeField
   {
      public string DateFormat { get; set; }

      protected override void Render(System.Web.UI.HtmlTextWriter output)
      {
         if (this.ItemContext.FormContext.FormMode == SPControlMode.Display)
         {
            if (!string.IsNullOrEmpty(DateFormat))
            {
               try
               {
                  DateTime selectedDate = (DateTime)base.ListItemFieldValue;
                  output.WriteEncodedText(selectedDate.ToString(DateFormat));
               }
               catch { }
            }
            else
            {
               base.Render(output);
            }
         }
         else
         {
            base.Render(output);
         }
      }
   }
}

U can use it in youre page layout like this:

<%@ Register Tagprefix="Webcontrols" Namespace="Webcontrols" Assembly="Webcontrols, Version=1.0.0.0, Culture=neutral, PublicKeyToken=868bd32625cae9fb" %>
Date: <WebControls:CustomDateTimeControl  FieldName="Date" DateFormat="dd MMMM yyyy" runat="server"></WebControls:CustomDateTimeControl>

In the control you can alter the text of the property DateFormat=”dd MMMM yyyy”
In this case dd MMMM yyyy causes the date to be renderd like: 18 september 2010

In this document there are some examples for the dateformat:

Date and Time Format Strings

Categories: Sharepoint Tags:
Comments are closed.