# Calculate hours from two text fields

I have a custom object called Log.

It has two fields : StartTime__c and Endtime__c.

R1.StartTime__c = '05:58 am';

R1.EndTime__c = '11:54 pm';

The number of hours between StartTime__c and EndTime__c is 17.87

Is there any way I can derive this number value via code or is it possible to build a formula field that can come up with this ?

• Why not just use `Time` fields instead? – Adrian Larson Aug 7 '18 at 4:31
• @AdrianLarson - Classic we have to enter value manually, it will not work as picklist that how it's working in lightning. Can you please tell me the data type which you have used for Start Time and End Time, I believe it should be text. Can you confirm? – Prem Anandh Aug 7 '18 at 4:49
• Are you not considering the dates here? – Naval Sharma Aug 7 '18 at 6:28

wilfred,

You must convert the time to Integer/Decimal/Long datatype in order to calculate the hours. You must use an ISO 8601 date, specifically something like:

2016-10-30 15:27:02.000

You must embed the time to some date. The hours can be calculated if you convert the string into DateTime and then use the getTime() method which returns the number of milliseconds of type Long. Here is a working Example:

``````String strDate1 = '2017-07-21 05:58:00';
String strDate2 = '2017-07-21 23:54:00';
Long t1 = Datetime.valueOf(strDate1).getTime();
Long t2 = Datetime.valueOf(strDate2).getTime();
decimal Hours = decimal.valueof((t1 - t2)/(60*60));
decimal diff = (hours/1000);
system.debug('Expected Difference ::->'+ diff);
``````

I hope this helps!!

• great answer..Saumya...instead of 24 hour format..can i give am/pm like below ?String strDate1 = '2017-07-21 05:58:00am'; String strDate2 = '2017-07-21 11:54:00pm'; – Aaron Wilfred Aug 8 '18 at 5:12
• – Saumya Gaikwad Aug 8 '18 at 9:19