c# – 只是日期或时间
发布时间:2020-12-16 00:12:01 所属栏目:百科 来源:网络整理
导读:我是在想 .. 我有这样的对象 public class Entry{public DateTime? Date { get; set;} // This is just Datepublic DateTime? StartTime { get; set; } //This is just Timepublic TimeSpan Duration { get; set; } //Time spent on entry} 是否有比DateTime
我是在想 ..
我有这样的对象 public class Entry{ public DateTime? Date { get; set;} // This is just Date public DateTime? StartTime { get; set; } //This is just Time public TimeSpan Duration { get; set; } //Time spent on entry } 是否有比DateTime更合适的类型或更好的策略来处理时间和日期?没有必须在我的所有开始和结束时间添加DateTime.MinDate()的痛苦? —更新— 1 – 我希望能够在Entry对象上请求Date或StartTime是否为Null. 2 – 输入应允许用户输入持续时间而不指示日期.即使像DateTime.MinDate()这样的默认日期也似乎是一个糟糕的设计. (这就是为什么我选择TimeSpan而不是Start和EndTime) 解决方法
不要拆分存储数据的日期和时间组件.如果您愿意,可以提供属性以提取它们:
public class Entry { public DateTime StartPoint { get; set; } public TimeSpan Duration { get; set; } public DateTime StartDate { get { return StartPoint.Date; } } public TimeSpan StartTime { get { return StartPoint.TimeOfDay; } } public DateTime EndPoint { get { return StartPoint + Duration; } } public DateTime EndDate { get { return EndPoint.Date; } } public TimeSpan EndTime { get { return EndPoint.TimeOfDay; } } } 更新: public class Entry{ private DateTime _startPoint; public bool HasStartDate { get; private set; } public bool HasStartTime { get; private set; } public TimeSpan Duration { get; private set; } private void EnsureStartDate() { if (!HasStartDate) throw new ApplicationException("Start date is null."); } private void EnsureStartTime() { if (!HasStartTime) throw new ApplicationException("Start time is null."); } public DateTime StartPoint { get { EnsureStartDate(); EnsureStartTime(); return _startPoint; } } public DateTime StartDate { get { EnsureStartDate(); return _startPoint.Date; } } public TimeSpan StartTime { get { EnsureStartTime(); return _startPoint.TimeOfDay; } } public DateTime EndPoint { get { return StartPoint + Duration; } } public DateTime EndDate { get { return EndPoint.Date; } } public TimeSpan EndTime { get { return EndPoint.TimeOfDay; } } public Entry(DateTime startPoint,TimeSpan duration) : this (startPoint,true,duration) {} public Entry(TimeSpan duration) : this(DateTime.MinValue,false,duration) {} public Entry(DateTime startPoint,bool hasStartDate,bool hasStartTime,TimeSpan duration) { _startPoint = startPoint; HasStartDate = hasStartDate; HasStartTime = hasStartTime; Duration = duration; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |