我有两个DateTime
个对象:StartDate
和EndDate
。我想确保StartDate
在EndDate
之前。这是如何在C#中完成的?
答案 0 :(得分:179)
if (StartDate < EndDate)
// code
如果您只想要日期而不是时间
if (StartDate.Date < EndDate.Date)
// code
答案 1 :(得分:25)
if(StartDate < EndDate)
{}
DateTime支持普通比较运算符。
答案 2 :(得分:22)
您可以使用重载&lt;或者&gt;运算符。
例如:
DateTime d1 = new DateTime(2008, 1, 1);
DateTime d2 = new DateTime(2008, 1, 2);
if (d1 < d2) { ...
答案 3 :(得分:21)
if(dateTimeA > dateTimeB) Console.WriteLine("Do your own homework");
答案 4 :(得分:8)
if (StartDate>=EndDate)
{
throw new InvalidOperationException("Ack! StartDate is not before EndDate!");
}
答案 5 :(得分:6)
StartDate < EndDate
答案 6 :(得分:5)
查看DateTime.Compare方法
答案 7 :(得分:4)
这可能为时已晚,但为了让其他可能会遇到这种情况的人受益,我使用了IComparable
这样的扩展方法:
public static class BetweenExtension
{
public static bool IsBetween<T>(this T value, T min, T max) where T : IComparable
{
return (min.CompareTo(value) <= 0) && (value.CompareTo(max) <= 0);
}
}
将此扩展方法与IComparable
一起使用可使此方法更通用,并使其可用于各种数据类型,而不仅仅是日期。
您可以这样使用它:
DateTime start = new DateTime(2015,1,1);
DateTime end = new DateTime(2015,12,31);
DateTime now = new DateTime(2015,8,20);
if(now.IsBetween(start, end))
{
//Your code here
}
答案 8 :(得分:3)
我有相同的要求,但是当使用接受的答案时,它没有完成我的所有单元测试。对我来说,问题是你有一个新的对象,有开始和结束日期,你必须设置开始日期(在这个阶段你的结束日期的最小日期值为01/01/0001) - 这个解决方案确实通过了所有我的单元测试:
public DateTime Start
{
get { return _start; }
set
{
if (_end.Equals(DateTime.MinValue))
{
_start = value;
}
else if (value.Date < _end.Date)
{
_start = value;
}
else
{
throw new ArgumentException("Start date must be before the End date.");
}
}
}
public DateTime End
{
get { return _end; }
set
{
if (_start.Equals(DateTime.MinValue))
{
_end = value;
}
else if (value.Date > _start.Date)
{
_end = value;
}
else
{
throw new ArgumentException("End date must be after the Start date.");
}
}
}
它确实错过了开始和结束日期都可以是01/01/0001的边缘情况,但我并不担心。
答案 9 :(得分:2)
if (new DateTime(5000) > new DateTime(1000))
{
Console.WriteLine("i win");
}
答案 10 :(得分:0)
我想证明如果你转换为.Date你不需要担心小时/分钟/秒等:
[Test]
public void ConvertToDateWillHaveTwoDatesEqual()
{
DateTime d1 = new DateTime(2008, 1, 1);
DateTime d2 = new DateTime(2008, 1, 2);
Assert.IsTrue(d1 < d2);
DateTime d3 = new DateTime(2008, 1, 1,7,0,0);
DateTime d4 = new DateTime(2008, 1, 1,10,0,0);
Assert.IsTrue(d3 < d4);
Assert.IsFalse(d3.Date < d4.Date);
}
答案 11 :(得分:0)
如果您在ASP.NET中工作,则需要比较两个CalendarExtender对象之间的值,则比较日期的方式会稍有不同,但仍然非常相同。
if(calStartDate.SelectedDate > calEndDate.SelectedDate) {
MessageBox.ShowMessage("That's not how time works.");
}
其中将calStartDate和calEndDate设置为CalendarExtenders的ID。