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

前端 未结 10 628
遇见更好的自我
遇见更好的自我 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(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
    }
    

提交回复
热议问题