Insights

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

👋 Hey Sitecore Enthusiasts!

Sign up to our bi-weekly newsletter for a bite-sized curation of valuable insight from the Sitecore community.

What’s in it for you?

  • Stay up-to-date with the latest Sitecore news
  • New to Sitecore? Learn tips and tricks to help you navigate this powerful tool
  • Sitecore pro? Expand your skill set and discover troubleshooting tips
  • Browse open careers and opportunities
  • Get a chance to be featured in upcoming editions
  • Learn our secret handshake
  • And more!
Sitecore Snack a newsletter by Fishtank Consulting