11

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');

3 Answers 3

21

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.

3

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.

0

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);
3
  • 1
    You just use <, <=, >, >= as you would with numbers. This answer is probably misleading.
    – sfdcfox
    Apr 13, 2017 at 17:50
  • @Himanshu - That I checked already. I found that my above logic works fine. Not sure if this is good to move in Prod, though I dont see any alternate solution. Apr 13, 2017 at 17:50
  • @sfdcfox thanks for pointing out. i have updated answer.
    – Himanshu
    Apr 13, 2017 at 17:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.