A type for Date only in C# - why is there no Date type?

后端 未结 13 1920
暗喜
暗喜 2020-11-28 10:23

In our C# project we have the need for representing a date without a time. I know of the existence of the DateTime, however, it incorporates a time of day as well. I

13条回答
  •  伪装坚强ぢ
    2020-11-28 10:42

    Yeah, also System.DateTime is sealed. I've seen some folks play games with this by creating a custom class just to get the string value of the time as mentioned by earlier posts, stuff like:

    class CustomDate
    {
        public DateTime Date { get; set; }
        public bool IsTimeOnly { get; private set; }
    
        public CustomDate(bool isTimeOnly)
        {
            this.IsTimeOnly = isTimeOnly;
        }
    
        public string GetValue()
        {
            if (IsTimeOnly)
            {
                return Date.ToShortTimeString();
            }
    
            else
            {
                return Date.ToString();
            }
        }
    }
    

    This is maybe unnecessary, since you could easily just extract GetShortTimeString from a plain old DateTime type without a new class

提交回复
热议问题