Parsing A Date From Umbraco

This post is a quick reference about how to convert a date from Umbraco and convert it into a C# DateTime when using dynamic binding. When you work with Umbraco, I strongly recommend using a strongly-typed model approach, to learn why, I suggest you read this article, How To Write Safe Testable Code When Using Dynamic Model Binding With Umbraco MVC.

One problem when we work with Umbraco is that dates are returned as “2016-08-16T00:00:00”. If you try to put this in DateTime.Parse() method it won’t convert correctly. Instead, you need to use XmlConvert.ToDateTime(). For my requirement, I wanted to display a date in the following format

16th August 2016

As DateTime doesn’t provide a great way to deal with st, and I needed to write some custom code, I’ve included that snippet in the code below in case it helps someone out, but it’s not needed to do the conversion.

Node currentNode = Node.GetCurrent();
var property = currentNode.GetProperty(propertyName);
if (property == null)
return  string.Empty;
var postDate = XmlConvert.ToDateTime(postDatproperty.ValueAsString, XmlDateTimeSerializationMode.Utc);
var postDateAsString = FormatDate(postDate);
public string FormatDate(DateTime date)
{
var dayString = int.Parse(date.ToString("dd"));
var suffix = GetDaySuffix(dayString);
return $"{dayString}{suffix}{date.ToString(" MMMM yyyy")}";
}
private string GetDaySuffix(int day)
{
switch (day)
{
case 1:
case 21:
case 31:
return "st";
case 2:
case 22:
return "nd";
case 3:
case 23:
return "rd";
default:
return "th";
}
}

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

More Posts

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *