Salesforce DateTime fields can capture when meaningful events occur on a record: when it was created; when it was last updated; when a field changes to a specific value. This post describes how you can extract the days, hours, and minutes between 2 DateTime fields in a user-friendly format.
For this post, I’ll use the Salesforce Case object and the standard field LastModifiedDate to describe an approach for finding out how long its been since each Case has been modified, and displaying the elapsed time in an easy-to-read format using formula fields. To see the results of each step, you can create custom numeric formula fields and add them to your page layout. You’ll want to remove them later and only use the final custom text formula field.
For starters, we can just subtract the current DateTime from the LastModifiedDate.
The difference is displayed as the number of elapsed days, for example: 5.5432. Easy to report on, but not very user friendly.From the elapsed days, we can write a formula expression that will display the days, hours, and minutes. This approach converts the days into minutes, then determines how many full days there are; how many full hours are left over; and how many minutes are left over after the full hours.
First, we find the full days. The FLOOR() function returns the value to the left of the decimal point of any number. Since the subtraction results in a number of days, this one’s easy:
Next, we need to find how many hours are left over after the full days. Since there are 1440 minutes in a day, we can multiply the original difference by 1440 to convert it from days into minutes. The MOD() function returns the remainder of a division, so by taking the MOD() of the division by 1440, we’re left with just the minutes that don’t fit into full days. Dividing those minutes by 60 (60 minutes in an hour), and using FLOOR() again, we get the number of full hours:
The last step is to figure out how many minutes are left over after the full hours. Remember that FLOOR() returns the numbers to the left of the decimal, and MOD() returns whatever is left over. We can use the same formula for minutes that we used for hours, except we’ll use MOD() instead of FLOOR() to get the remaining minutes.
Putting it all together using the TEXT() function to convert each of the numeric parts to strings, and adding words creates an expression that is easy for the User to understand:
(Oh, yeah, I added the ROUND() function on the minutes to keep things neat).
You can learn about all the functions available in custom field formulas from the custom field formula edit screen. Click on a function in the list to see a short description, or follow the ‘Help on this function’ link.