How to Compare Two DateTime Values in Salesforce Apex

In our Salesforce org, the sales team needs to create follow-up tasks for opportunities that were closed within the last 30 days. To determine whether an opportunity was closed within the last 30 days, we need to find the difference between the closed date and the current date.

As a solution, I created an apex class that compares the current datetime value with the datetime when the opportunity was closed.

In this Salesforce tutorial, I will explain how to compare two datetime values in Salesforce Apex.

Compare Two DateTime Values in Salesforce Apex

In Salesforce Apex, there are many scenarios where it is required to compare two datetime values. You might want to check if two datetime values are equal, if one is earlier or later than the other, or if there is a difference between them.

In the steps below, we will discuss various methods for comparing two datetime values for different scenarios.

Compare DateTime Values in Salesforce Apex Using the DateTime.getTime() Method

In the steps below, we will compare two datetime values using the datetime.newInstance() method. In the debug, we will show the output of the datetime value that exceeds the other.

Now, open the Salesforce developer console and execute the code below in the Apex anonymous window.

DateTime dt1 = DateTime.newInstance(2024, 11, 16, 10, 0, 0);
DateTime dt2 = DateTime.newInstance(2024, 11, 14, 12, 0, 0);

Long time1 = dt1.getTime();
Long time2 = dt2.getTime();

if (time1 == time2) {
    System.debug('Both DateTime values are equal.');
} else if (time1 < time2) {
    System.debug('dt1 is earlier than dt2.');
} else {
    System.debug('dt1 is later than dt2.');
}

In the above code, we have entered date values d1 = 2024/11/16 and d2 = 2024/11/14. Here, d1 is the later date than d2.

According to the conditionals in the above code, the debug output is displayed as dt1 is later than dt2.

Salesforce Apex compare two datetime values

This way, we can compare two datetime values in Salesforce Apex using the DateTime.getTime() method and adding conditionals.

Compare DateTime Values in Salesforce Apex using the DateTime.sort() Method

In Salesforce Apex, we can use the DateTime.sort() method to calculate the difference between two DateTime values. This method returns the difference in milliseconds. Therefore, we should use this method to compare close DateTime values that require comparing the time component of the DateTime field.

In the code below, I will compare the datetime fields System.today() and System.Now() and calculate the difference between these two in milliseconds.

Now, open the Salesforce developer console and enter the code below in the Apex anonymous window and execute it.