Using DateTime And Date Fields In Sitecore

Save The Pain

Years ago when I first worked with Date fields in Sitecore, specifically DateTime fields, I made some mistakes. I did a lot of manual parsing and converting.

The Date and DateTime fields in Sitecore can be tricky to work with. Years ago when I started in Sitecore, I definitely made some mistakes with dates & times in Sitecore. Hopefully I can share some of my experience and save you some grief.

The Nature Of DateTime

Start with a DateTime field in template:

See how it's rendered as a field:

Now we'll flip the content editor to raw values to begin to reveal its secrets:

It goes from hard on the eyes to hard on the brain in one-click.

What you're seeing there is an ISO 8601 formatted date-time. Its format is yyyyMMddThhmmss.

Manipulating Sitecore's DateTime Field in .NET

There is no DateTimeField only a DateField. This makes sense because behind the scenes a DateTime and Date share the code base. They only difference is they way they display in the content editor. Both store ISO 8601 values.

In hopes of easily manipulation, we'll cast the field as a DateField:

DateField dateField = (DateField)item.Fields["Date Created"];
// DateTime object
var dateTime = dateField.DateTime;
// String
var year = dateField.ToString(); 

That's okay for reading the values, but it doesn't help for easily setting a new value.

Setting A DateTime Field

DateUtil is a very helpful class, full of static methods that make our lives easier. Thank you, DateUtil.

I most frequently have to set dates when importing / migrating content, so I'm using an excerpt from CSV parsing code as the sample:

// i.e. 10/3/2013 19:26	10/11/2013 11:13
var csvDate = data[CsvFields.Date];
// DateTime object
var dateTime = DateTime.Parse(csvDate);
// Raw value for DateTime field in Sitecore
var isoDate = DateUtil.ToIsoDate(dateTime);

That's the basic of what you'll need. Be sure to cast your DateTime fields to DateField and lean generously on the DateUtil helper class. It's full of many useful, life-simplifying methods.

This article was authored using Markdown for Sitecore.

Meet Dan Cruickshank


Dan is the founder of Fishtank. He's a multi-time Sitecore MVP and Coveo MVP award winner. Outside of technology, he is widely considered to be a top 3 father (routinely receiving "Father of the Year" accolades from his family) and past his prime on the basketball court.

Connect with Dan