如何在C#中检查一个DateTime是否大于另一个


105

我有两个DateTime对象:StartDateEndDate。我想确定StartDate之前EndDate。如何在C#中完成?

Answers:





23

您可以使用重载的<或>运算符。

例如:

DateTime d1 = new DateTime(2008, 1, 1);
DateTime d2 = new DateTime(2008, 1, 2);
if (d1 < d2) { ...




5

这可能为时已晚,但是为了使可能会偶然发现此问题的其他人受益,我使用了一种扩展方法,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
}

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的极端情况,但我对此并不担心。



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);
    }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.