10

I have a date field in a tridion schema which, when published using the standard DD4T templates, becomes the component field:

  <Field xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" FieldType="Date" XPath="tcm:Metadata/custom:Metadata/custom:date">
          <Name>dates</Name>
          <Values>
            <string>16/08/2013 18:47:16</string>
          </Values>
          <NumericValues />
          <DateTimeValues>
            <dateTime>2013-08-16T18:47:16</dateTime>
          </DateTimeValues>
          <LinkedComponentValues />
          <EmbeddedValues />
          <Keywords />
    </Field>

Does DD4T provide a method for converting the values of a date field value (string) into a DateTime object?

e.g. from dateTimeString to DateTime:

string dateTimeString metadataFields["dates"].Values[0];
10

I was one step ahead of myself. DD4T provides the method IField.DateTimeValue, therefore you don't need to get the string value then convert to a DateTime, you simply go straight to the DateTime (as mpaton points out, ensure to check for values when putting the code to production):

if (page.MetadataFields.ContainsKey("modifyDate") && page.MetadataFields["modifyDate"] != null && page.MetadataFields["modifyDate"].DateTimeValues.Count > 0)
{   List<DateTime> myDates = metadataFields["dates"].DateTimeValues;
    DateTime myDate = myDates[0];
    ...
}
2
  • 2
    Be careful that myDates[0] is not null or you'll get an Exception when you instantiate myDate – mpaton Jun 14 '13 at 21:25
  • 5
    For special field types like dates, numbers, links etc, dd4t provides a number of 'lists of values', like DateTimeValues, NumberValues, etc. Note that you must always use these lists, even if the fields are single value. The shortcut IField.Value only applies to strings (text and rich text fields). – Quirijn Jun 15 '13 at 8:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.