[SalesForce] How to find min of two dates in apex

I am trying to find min of two dates.

I used MIN(date1,date2) but I am facing the following error:
"Method does not exist or incorrect signature: void min(Date, Date)"

How can we find the minimum of two dates?

Best Answer

Probably best to add your own static method either into the class where you need the minimum (make it private) or a utility class (make it public). This version handles nulls:

private static Date min(Date d1, Date d2) {
    if (d1 != null && d2 != null) return d1 < d2 ? d1 : d2;
    else if (d1 != null) return d1;
    else if (d2 != null) return d2;
    else return null;
}