Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

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 something like:

 if (Math.Min(Date1, Date2) < MINIMUM_ALLOWED_DATE) {       //not allowed to do this  } 

Obviously the above Math.Min doesn't work because they're dates.

like image 863
hawbsl Avatar asked Dec 31 '09 13:12

hawbsl


People also ask

What does Math min mean?

Min means Minimum. So yes, it's a function that, taken two elements, gives you the minimum of those.

What is Math min and Math Max?

Math. min() to find the minimum of n elements. Math. max() to find the maximum of n elements.

What does Math min do in C#?

The Math. Min() method in C# is used to return the larger of two specified numbers. This method works for both the numbers being Double, Decimal, Int16, Int32, etc.


1 Answers

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() 
like image 58
mmx Avatar answered Oct 12 '22 18:10

mmx