BBo*_*org 3 c# time datetime date
我是在想 ..
我有这样的对象
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
}
Run Code Online (Sandbox Code Playgroud)
是否有比DateTime更合适的类型或更好的策略来处理时间和日期?没有必须在我的所有开始和结束时间添加DateTime.MinDate()的痛苦?
---更新---
1 - 我希望能够在Entry对象上请求Date或StartTime是否为Null.
2 - 输入应允许用户输入持续时间而不指示日期.即使像DateTime.MinDate()这样的默认日期也似乎是一个糟糕的设计.(这就是为什么我选择TimeSpan而不是Start和EndTime)
你可以使用一个TimeSpan你StartTime和EndTime性能.这就是DateTime.TimeOfDay物业回归的原因.
还有一个DateTime.Date属性,它返回一个DateTime时间元素设置为午夜.
话虽如此,我可能会建议Date完全放弃你的财产DateTime,并在你StartTime和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; } }
}
Run Code Online (Sandbox Code Playgroud)
更新:
如果要为日期和时间设置空值,可以为其添加属性,而无需拆分日期和时间:
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, true, duration) {}
public Entry(TimeSpan duration)
: this(DateTime.MinValue, false, false, duration) {}
public Entry(DateTime startPoint, bool hasStartDate, bool hasStartTime, TimeSpan duration) {
_startPoint = startPoint;
HasStartDate = hasStartDate;
HasStartTime = hasStartTime;
Duration = duration;
}
}
Run Code Online (Sandbox Code Playgroud)