How to set the default value of DateTime to empty string?

会有一股神秘感。 提交于 2019-12-04 16:49:49

How about just changing your property to link to a private field of DateTime e.g.:

public string Raised_Time
{
  get
  {
    if(fieldRaisedTime == DateTime.MinValue)
    {
      return string.Empty();
    }
    return DateTime.ToString();
  }
  set
  {
    fieldRaisedTime = DateTime.Parse(value,   System.Globalization.CultureInfo.InvariantCulture);
  }
}

I would use a Converter for this because it's something I can easily see reusing in the future. Here's one I used to use that took a string value of the DateFormat as the ConverterParameter.

public class DateTimeFormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if ((DateTime)value == DateTime.MinValue)
            return string.Empty;
        else
            return ((DateTime)value).ToString((string)parameter);
    }


    public object ConvertBack(object value, System.Type targetType, object parameter, CultureInfo culture)
    {
        throw new System.NotImplementedException();
    }
}

I see two easy options to solve this:

  1. You use the Nullable data type DateTime?, so that you can store null instead of DateTime.MinValue if the alarm time is not set.

  2. You can use a converter, here is an example.

fearofawhackplanet

I use a nullable datetime for this, with an extension method like:

 public static string ToStringOrEmpty(this DateTime? dt, string format)
 {
     if (dt == null)
        return string.Empty;

     return dt.Value.ToString(format);
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!