只是日期或时间

时间:2009-08-27 13:09:06

标签: c# datetime date time

我只是想知道..

我有这样的对象

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的原因)

4 个答案:

答案 0 :(得分:6)

您可以为StartTimeEndTime属性使用TimeSpan。这就是DateTime.TimeOfDay属性返回的内容。

还有DateTime.Date属性返回DateTime,时间元素设置为午夜。

话虽如此,我可能会建议完全抛弃您的Date媒体资源,并在DateTime StartTime中存储完整的EndTime s(即日期时间)和{{1}}属性。

答案 1 :(得分:6)

不要拆分存储数据的日期和时间组件。如果您愿意,可以提供属性来提取它们:

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;
   }

}

答案 2 :(得分:1)

您最好将参考文献保留为DateTime。如果您只存储时间,则当Entry超过24小时时,您就会遇到问题。将它们存储为DateTime s,就像现在一样,并应用任何必要的格式来代表最终用户的时间部分。

答案 3 :(得分:0)

我想赞美Guffa's answer还有两个最佳做法:

  1. 将所有日期以UTC格式存储在数据库中。
  2. 避免使用System.DateTime和favor System.DateTimeOffset
    1. SQL Server 2008的datetimeoffset类型等同于DateTimeOffset。