Whay is the correct way to compare two dates in Apex? I tried the following:

Date d1 = Date.today();
Date d2 = Date.today();

if(d2 > d1)
else if(d2 < d1)
else if(d1 == d2)

3 Answers 3


Using the standard comparison operators <, >, ==, !=, <=, and >= is the correct way to compare dates (and datetimes as well)

It isn't directly stated in documentation, at least not that I can find, but we can infer that these operators are meant to work on dates from the documentation on Apex expression operators (emphasis mine)

> x > y Greater than operator.

If x is greater than y, the expression evaluates to true. Otherwise, the expression evaluates to false.


  • The comparison of any two values can never result in null.
  • If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the expression is false.

(and the same for the other operators I listed).

If Dates/Datetimes were not meant to be used with these operators, I would expect that they wouldn't be mentioned in the documentation like this (and there would likely be comparison methods on the Date/Datetime classes themselves).

Also, if the comparison operators did not support date/datetime, you would get an error of some sort when you tried to save code that tried to use it.


You can use daysBetween if you want the number of days between two dates, but the six comparison operators (less than, greater than, less or equal, greater or equal, equals, and not equals), all operate the same way as they do on numbers.


Date class has isSameDay Method but there is no Date class method which can get less than or grater than. You have to use <, <=, >, >= for that purpose. Check all the available methods in Date class

date myDate = date.today();
date dueDate = date.newInstance(2008, 1, 30);
boolean dueNow = myDate.isSameDay(dueDate);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .