A System's Default Regional Iso Code and the Trouble of Parsing Different Date Formats

I recently migrated a project to a new environment, only to find that rendering a date field was inconsistently working. Not Sitecore's fault, but I've never seen this before, and I know as a seasoned developer I should have all (ok most) of the answers. It's a good catch and I wanted to share.

Ok let's get right down to finding the issue. You can grab a date field value in Sitecore using the following code.

var fieldDateTime = item.RenderField("Event Date", "disable-web-editing=true")?.ToString();

The RenderField method is going to return the date stored in the Event Date field. Pretty straightforward but here's the catch. It returns the date formatted per the system short date setting, and that needs to be compatible with what format you need it in. Here's an example:

To start, check the system's short date format by going to Control Panel -> Change date, time, or number formats




Sitecore will return a value of 30/01/2024, but our code will try to format it into yyyy/MM/dd, which causes the exception “String was not in a recognized as a valid DateTime”. It's tricky since the exception is inconsistent. Maybe some dates have a day between 1-12 so it parses incorrectly, but without excpetion as seen here:

string dateFormat = "dd/MM/yyyy";
var fieldDateTime = item.RenderField(("Event Date", "disable-web-editing=true")?.ToString();
string eventDate = (string.IsNullOrEmpty(fieldDateTime)) ?
                    DateTime.MinValue.ToString(dateFormat) :
                    System.Convert.ToDateTime(fieldDateTime).ToString(dateFormat);

Keep in mind this is a sample; Don't store field names or formats like this. Get it from a central location. 


An Easy Resolution

Now, you can either change the system's date settings, but it's best to use the Sitecore setting of DefaultRegionalIsoCode:

<setting name="DefaultRegionalIsoCode" value="en-CA" />

After this change the date format will be 2024-01-30, and can be properly parsed into the formats we need.