How to Compare Two Dates in Apex?

  • 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)
        System.debug('TRUE');
    else if(d2 < d1)
        System.debug('FALSE');
    else if(d1 == d2)
        System.debug('SAME');
    
  • Derek F

    Derek F Correct answer

    4 years ago

    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.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used