不要拆分存儲數據的日期和時間組件。您可以提供的屬性,如果你想提取那些:
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, 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;
}
}
當你的EndTime在第二天會發生什麼? – ChrisF 2009-08-27 13:12:52
你說得對Chris不好。在上面的例子中,我打出了endtime,只有Date,StartTime和Duration。好點 – BBorg 2009-08-27 13:19:59
@Borg:在這種情況下,爲什麼不把'Date'屬性完全拋棄,並且'StartTime'表示日期*和*時間。畢竟,這就是'DateTime'的用途! – LukeH 2009-08-27 13:21:38