10.5
  1. Access field values

Access Date and Datetime fields

You can use the Sitecore.Data.Fields.DateField class to access data template fields of type Date and Datetime. The Sitecore.Data.Fields.DateField.Value property contains the date and time as a string in the ISO format used by Sitecore (yyyyMMddTHHmmss).

Note

For more information about .NET date format patterns, see http://msdn.microsoft.com/en-us/library/73ctwf33.aspx.

You can convert a value in the ISO format to a System.DateTime structure using the Sitecore.DateUtil.IsoDateToDateTime method. For example, to access the Date or Datetime field named DateTimeField in the /Sitecore/Content/Home item in the Master database:

Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");

Sitecore.Data.Items.Item home = master.GetItem("/sitecore/content/home");

Sitecore.Data.Fields.DateField dateTimeField = home.Fields["datetimefield"];

string dateTimeString = dateTimeField.Value;

DateTime dateTimeStruct = Sitecore.DateUtil.IsoDateToDateTime(dateTimeString);

Alternatively, you can access the Sitecore.Data.Fields.DateField.DateTime property, which contains a System.DateTime structure representing the same value. For example, to access the Date or Datetime field named DateTimeField in the /Sitecore/Content/Home item in the Master database as a System.DateTime structure:

Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");

Sitecore.Data.Items.Item home = master.GetItem("/sitecore/content/home");

Sitecore.Data.Fields.DateField dateTimeField = home.Fields["datefield"];

DateTime dateTimeStruct = dateTimeField.DateTime;

You can update the value of a Date or Datetime field by updating the Sitecore.Data.Fields.DateField.Value property to a string in the ISO format. You can use the Sitecore.DateUtil.ToIsoDate method to convert a System.DateTime structure to the ISO format. For example, to update the value of the Datetime field named DateTimeField in the /Sitecore/Content/Home item in the Master database to the current system date:

Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");

Sitecore.Data.Items.Item home = master.GetItem("/sitecore/content/home");

Sitecore.Data.Fields.DateField dateTimeField = home.Fields["datetimefield"];

if (dateTimeField != null)
{
    home.Editing.BeginEdit();
    dateTimeField.Value = Sitecore.DateUtil.ToIsoDate(DateTime.Now);
    home.Editing.EndEdit();
}
Note

If the user has not specified a value for a field of type Date or Datetime, then the Sitecore.Data.Fields.DateField.Value property contains an empty string and the Sitecore.Data.Fields.DateField.DateTime property contains System.DateTime.MinValue.

Tip

By default, a field of type Date contains a time value of midnight.

If you have suggestions for improving this article, let us know!