Search code examples
sensenet

Sensenet DateTime Field Default Value


When DateTime field is left blank, Sensenet displays (system default) '01/01/01 12:00' in the content browse mode. Can it display no value since it was not entered by users?


Solution

  • You can also solve this with server side code in your content handler.

    If you instantiate a new DateTime object its default value is 1/1/0001 12:00:00 AM, also specified as DateTime.MinValue. DateTime.MaxValue is 12/31/9999 11:59:59 PM. You then test for DateTime.MinValue to address formatting.

    If you have content where you will be formatting and displaying dates a lot, it is often simpler in your Content Type Definition (CTD) to define a string field that corresponds to the date field. For example, your CTD could have fields like this:

    <Field name="ReviewDate" type="DateTime" >
      <DisplayName>Review Date</DisplayName>
    </Field>
    
    <Field name="ReviewDateStr" type="ShortText" >
      <DisplayName>Review Date</DisplayName>
    </Field>
    

    Then in your content handler, you create a read only getter to display the ReviewDate:

    private const string REVIEWDATESTRPROPERTY = "ReviewDateStr";
    [RepositoryProperty(REVIEWDATESTRPROPERTY, RepositoryDataType.String)]
    public virtual string ReviewDateStr
    {
        get
        {
            if (ReviewDate == DateTime.MinValue)
            {
                return "n/a";      // Default string if date is not set.
            }
            return ReviewDate.ToString();   // Add date formatting here.
        }
    }
    

    Alternatively, you can create a field control that does that same thing.