Equivalent of Math.Min & Math.Max for Dates?

后端 未结 9 1909
渐次进展
渐次进展 2020-12-13 05:16

What\'s the quickest and easiest way to get the Min (or Max) value between two dates? Is there an equivalent to Math.Min (& Math.Max) for dates?

I want to do som

相关标签:
9条回答
  • 2020-12-13 06:04

    There's no built in method to do that. You can use the expression:

    (date1 > date2 ? date1 : date2)
    

    to find the maximum of the two.

    You can write a generic method to calculate Min or Max for any type (provided that Comparer<T>.Default is set appropriately):

    public static T Max<T>(T first, T second) {
        if (Comparer<T>.Default.Compare(first, second) > 0)
            return first;
        return second;
    }
    

    You can use LINQ too:

    new[]{date1, date2, date3}.Max()
    
    0 讨论(0)
  • 2020-12-13 06:05

    Linq.Min() / Linq.Max() approach:

    DateTime date1 = new DateTime(2000,1,1);
    DateTime date2 = new DateTime(2001,1,1);
    
    DateTime minresult = new[] { date1,date2 }.Min();
    DateTime maxresult = new[] { date1,date2 }.Max(); 
    
    0 讨论(0)
  • 2020-12-13 06:05

    If you want to call it more like Math.Max, you can do something like this very short expression body:

    public static DateTime Max(params DateTime[] dates) => dates.Max();
    [...]
    var lastUpdatedTime = DateMath.Max(feedItemDateTime, assemblyUpdatedDateTime);
    
    0 讨论(0)
提交回复
热议问题