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 it, 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";
				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

Back to top
var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-35662136-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + ''; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();