Calculate the difference between 2 datetimes in hours or minutes or days easily with the below tricks. You can calculate the difference in formula field or Visualforce page tag or in apex programming too. There are many other methods available in Datetime class of Salesforce to convert the Datetime values. To check out the list of the available methods Click Here.
To calculate the difference between the 2 dates Click Here.
For the difference between 2 DateTimes fields, check:
- Formula Field
1 2 3 4 5 |
Minutes -> (NOW()-CreatedDate)*24*60 Hours -> (NOW()-CreatedDate)*24 Days -> (NOW()-CreatedDate) |
- Visualforce Page
1 2 3 4 5 6 7 |
<apex:page standardController="Account" showHeader="false" sidebar="false"> <apex:outputText value="Days : {! (NOW() - account.CreatedDate)}"></apex:outputText> <apex:outputText value="Hours : {! (NOW() - account.CreatedDate)*24}"></apex:outputText> <apex:outputText value="Minutes : {! (NOW() - account.CreatedDate)*24*60}"></apex:outputText> </apex:page> |
- APEX
1 2 3 4 5 6 7 8 9 10 11 12 13 |
DateTime startDate = DateTime.newInstance(2020,1,1,3,0,0); DateTime endDate = DateTime.newInstance(2020,1,3,6,0,0); Decimal minutes = Integer.valueOf((endDate.getTime() - startDate.getTime())/(1000*60)); System.debug('Minutes : ' + minutes); Decimal hours = Integer.valueOf((endDate.getTime() - startDate.getTime())/(1000*60*60)); System.debug('Hours : ' + hours); Decimal days = Integer.valueOf((endDate.getTime() - startDate.getTime())/(1000*60*60*24)); System.debug('Days : ' + days); |
You can also use other methods available in the SF Datetime class for various DateTime conversions.
To get a specific parameter from your datetime variable, use .hour(), .minute(), .date(), .day(), .dateGMT(), etc.
Also Check:
For any queries or suggestions, comment below.
Cheers … Happy Coding … 🙂