Equivalent of Math.Min & Math.Max for Dates?
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.
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()
There is no overload for DateTime values, but you can get the long value Ticks
that is what the values contain, compare them and then create a new DateTime value from the result:
new DateTime(Math.Min(Date1.Ticks, Date2.Ticks))
(Note that the DateTime structure also contains a Kind
property, that is not retained in the new value. This is normally not a problem; if you compare DateTime values of different kinds the comparison doesn't make sense anyway.)
How about:
public static T Min<T>(params T[] values)
{
if (values == null) throw new ArgumentNullException("values");
var comparer = Comparer<T>.Default;
switch(values.Length) {
case 0: throw new ArgumentException();
case 1: return values[0];
case 2: return comparer.Compare(values[0],values[1]) < 0
? values[0] : values[1];
default:
T best = values[0];
for (int i = 1; i < values.Length; i++)
{
if (comparer.Compare(values[i], best) < 0)
{
best = values[i];
}
}
return best;
}
}
// overload for the common "2" case...
public static T Min<T>(T x, T y)
{
return Comparer<T>.Default.Compare(x, y) < 0 ? x : y;
}
Works with any type that supports IComparable<T>
or IComparable
.
Actually, with LINQ, another alternative is:
var min = new[] {x,y,z}.Min();
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();
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);