How to Compare Two Dates in Apex?

Yes, 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.

Note:

  • 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).

+edit:

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.

Tags:

Apex