Hello friends, In this post you will see, how to get time difference in hour using apex code. In other words, how to subtract time in apex.

Datetime difference in hour in apex

Use the following code snippet to get time difference in hour.

1) First Method

 datetime startDate = Datetime.now().addhours(-2);
System.debug('startDate '+startDate);
datetime endDate = Datetime.now();
System.debug('endDate '+endDate);
DateTime startDateTime = DateTime.newInstance(Date.today(), startDate.time());
System.debug('startDateTime '+startDateTime);
DateTime endDateTime = datetime.newInstance(Date.today(), endDate.time());
System.debug('endDateTime '+endDateTime);
Long timeAvailable = endDateTime.getTime() - startDateTime.getTime();
timeAvailable /= 3600000;
System.debug('Time Difference *^^* '+timeAvailable);

Output:

 2) Second Method

 Junction__c acc = [Select StartDate__c, EndDate__c From Junction__c WHERE Id='a010K00002X1NvN'];
Long startDatetime = acc.StartDate__c.getTime();
Long endDatetime = acc.EndDate__c.getTime();
Decimal diffMilliSecs = Decimal.valueOf(endDatetime - startDatetime);

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

Output:

 Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.