Tag Archives: Date

Calculate The Difference Between Two DateTime Fields In Salesforce Apex

Sample Code:

Account acc = [Select Id, Name, CreatedDate, LastModifiedDate From Account LIMIT 1];
Long createdDateTime = acc.CreatedDate.getTime();
Long modifiedDateTime = acc.LastModifiedDate.getTime();
Decimal diffMilliSecs = Decimal.valueOf(modifiedDateTime - createdDateTime);

Decimal dDays = diffMilliSecs/1000/60/60/24;
Integer iDays = Integer.valueOf(math.floor(dDays));
Decimal remainderDays = dDays- iDays;

Decimal dHours = remainderDays * 24;
Integer iHours = Integer.valueOf(math.floor(dHours));
Decimal remainderHours = dHours - iHours;

Decimal dMinutes = remainderHours * 60;
Integer iMinutes = Integer.valueOf(math.floor(dMinutes));
Decimal remainderMinutes = dMinutes - iMinutes;

Decimal dSeconds = remainderMinutes * 60;
Integer iSeconds = Integer.valueOf(math.floor(dSeconds));
Decimal remainderSeconds = dSeconds - iSeconds;

System.debug('Days: ' + iDays+' - '+'Hours: ' + iHours+' - '+'Minutes: ' + iMinutes+' - '+'Seconds: ' + iSeconds);