Publishing Page Layout DateTimeField formatting
I wanted to have my DateTimeField show up with a different format than the 'short date' value that it defaults to. Unfortunately you can't just add a date format string to a field property to make this work. I've seen a few alternative ways to do this involving extending the DateTimeField control. But I didn't like those options and felt the way I finally figured out was a little nicer (in my opinion).
Here's what I did:
1. Add a code behind page to your page layout and wire it up. If you don't know how to do this watch this short video by Andrew Connell. The 2nd part has to do with Page Layouts but you do the exact same thing as he does in the first part with the master page.
2. Add an 2 EditModePanels to your page layout like so:
<PublishingWebControls:EditModePanel runat="server" ID="DateEditModePanel">
<SharePointWebControls:DateTimeField ID="ArticleDateControl" runat="server" FieldName="NewsArticleDate" />
</PublishingWebControls:EditModePanel>
<PublishingWebControls:EditModePanel runat="server" ID="DateDisplayModePanel" PageDisplayMode="Display">
<asp:Label runat="server" ID="lblFormatDate" />
</PublishingWebControls:EditModePanel>
3. Add the following control references to your code-behind class
protected Label lblFormatDate;
protected DateTimeField ArticleDateControl;
4. Add the following code in your code behind page:
protected override void OnLoad(EventArgs e)
{
if (this.ArticleDateControl != null)
{
string dateString = "";
try
{
dateString = Convert.ToDateTime(this.ArticleDateControl.ItemFieldValue).ToString("MMMM d, yyyy");
}
catch
{
dateString = "";
}
lblFormatDate.Text = dateString;
}
}
5. Do the dance of joy.
Comments
Regards,
Tomas