How to check if one DateTime is greater than the other in C#

前端 未结 10 631
遇见更好的自我
遇见更好的自我 2021-02-03 16:28

I have two DateTime objects: StartDate and EndDate. I want to make sure StartDate is before EndDate. How is this

相关标签:
10条回答
  • 2021-02-03 16:53

    This is probably too late, but to benefit other people who might stumble upon this, I used an extension method do to this using IComparable like this:

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

    Using this extension method with IComparable makes this method more generic and makes it usable with a wide variety of data types and not just dates.

    You would use it like this:

    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
    }
    
    0 讨论(0)
  • 2021-02-03 16:54
    StartDate < EndDate
    
    0 讨论(0)
  • 2021-02-03 17:02
    if (StartDate < EndDate)
       // code
    

    if you just want the dates, and not the time

    if (StartDate.Date < EndDate.Date)
        // code
    
    0 讨论(0)
  • 2021-02-03 17:09
    if(StartDate < EndDate)
    {}
    

    DateTime supports normal comparision operators.

    0 讨论(0)
  • 2021-02-03 17:12

    You can use the overloaded < or > operators.

    For example:

    DateTime d1 = new DateTime(2008, 1, 1);
    DateTime d2 = new DateTime(2008, 1, 2);
    if (d1 < d2) { ...
    
    0 讨论(0)
  • 2021-02-03 17:12

    Check out DateTime.Compare method

    0 讨论(0)
提交回复
热议问题