How to Display a Readable Sitecore Date or DateTime Field in a View

Easy Boilerplate For You

Dates have always been a pain for developers. This boilerplate code may help you out.

Here's our view file:


@using Sitecore.Mvc.Presentation
@using Sitecore.Mvc
@using Sitecore.Mvc.Extensions
@{ var currentItem = Html.Sitecore().CurrentItem; }

// Your exact syntax here may vary depending on your Sitecore version. IsPageEditor can also be IsExperienceEditor
@if (Sitecore.Context.PageMode.IsPageEditor)
{
	<p><b>Published:</b> @Html.Sitecore().Field("Published Date", currentItem) </p>
}
else
{
	<p><b>Published:</b> @ViewHelper.GetReadableDate("Published Date", currentItem)</p>
}

Over in a helper class, you'll need to write the following methods:


public static DateTime GetDate(string fieldName, Item item)
{
	var field = item.Fields[fieldName];
	if (field == null) return DateTime.Now;

	if (!DateUtil.IsIsoDate(field.Value)) return DateTime.Now;

	var dateTime = ((DateField)field).DateTime;

	return dateTime;
}

public static string GetReadableDate(string fieldName, Item item)
{
	if (item == null || fieldName.IsWhiteSpaceOrNull() || String.IsNullOrWhiteSpace(item[fieldName])) return "No Date Specified";
	
	var dateTime = GetDate(fieldName, item);

	return dateTime.ToString("MMMM dd, yyyy");
}

Happy coding!

Marcel

Fish