In this tutorial, you will learn about a good practice to render formatted dates when using a website powered by Umbraco CMS. You will learn how to convert a date stored within Umbraco and convert it into a C# DateTime when using dynamic binding.
One problem when we work with Umbraco with plugins like uSiteBuilder or ModelBuilder return dates selected by content editors with the CMS in this format, "2016-08-16T00:00:00". If you try to copy this string value into the
DateTime.Parse() method it won't work. Instead, you first need to use
XmlConvert.ToDateTime(). After converting the data string stored in Umbraco to
DateTimeyou can then format it as required.
I wanted to display a date on a page, in the following format:
16th August 2016
When rendering dates on a web page, you will often need to render dates using the same format in multiple places. This is why putting your date code in a shared helper method is a good idea. Using a helper method to render similarly formatted dates will help you to avoid violating the DRY principle! This approach is a good practice I recommend you follow. The code to write this helper could look like this:
This code takes the property in Umbraco, converts it, then formats it. The result is a string that can be rendered on a website. This method can be shared across all your different document types. Happy Coding 🤘