# Calculate difference between two Times

Given two Time variables (not DateTimes), how can I calculate the difference (in minutes, seconds, or milliseconds, doesn't matter) between the two?

``````Time startTime = user.Appointment_Start_Time__c;
Time endTime = user.Appointment_End_Time__c;
Long timeAvailable = (endTime.minute() - startTime.minute());
System.debug(timeAvailable);
``````

This returns a `-9` with the following variables:

``````startTime | 35100000
endTime | 48600000
``````

and these user assignments:

If I use `millisecond()` it returns a `0`. What's going on?

The hour(), minute(), second(), and millisecond() methods return the value as you'd expect if you were telling someone what time it is. For example, if I say it is ten minutes past six (assume early morning), hour returns 6, minute returns 10, etc. `hour` returns a value from 0 to 23, `minute` from 0 to 59, `second` from 0 to 59, and `millisecond` from 0 to 999.

To get a difference in time, subtract the milliseconds via getTime:

``````Long timeAvailable = endTime.getTime() - startTime.getTime();
``````

The getTime method returns the number of milliseconds since Jan 1st, 1970, midnight GMT. This math gives you a difference in milliseconds. From there, to get the minutes, divide by 60,000:

``````timeAvailable /= 60000;
``````

Note that even though milliseconds are an attribute of datetime, the database does not currently store or return milliseconds, so millisecond() called on a value from the database will always be zero.

Full Example:

``````DateTime startTime = DateTime.newInstance(Date.today(), user.Appointment_Start_Time__c);
DateTime endTime = datetime.newinstance(Date.today(), user.Appointment_End_Time__c);
Long timeAvailable = endTime.getTime() - startTime.getTime();
timeAvailable /= 60000;
System.debug(timeAvailable);
``````

Without converting to DateTime values, you need to calculate the hours and minutes, and subtract the difference;

``````Time startTime = user.Appointment_Start_Time__c;
Time endTime = user.Appointment_End_Time__c;
Long timeAvailable = (endTime.hour() * 60 + endTime.minute()) -
(startTime.hour() * 60 + startTime.minute());
``````
• This gives an `Unexpected token 'timeAvailable'.` for the `Long` assignment.
– t56k
Commented Nov 12, 2018 at 4:25
• @CD-RUM Wait, you're using time fields, aren't you? I just realized that. One more sec.
– sfdcfox
Commented Nov 12, 2018 at 4:42
• @CD-RUM See edit; we convert the time to datetimes, then subtract the difference between those. It's not the only way to do this, but probably the easiest.
– sfdcfox
Commented Nov 12, 2018 at 4:44
• Ah, thank-you so much! It constantly surprises me how often you're able to help me.
– t56k
Commented Nov 12, 2018 at 5:06
• would the number of minutes go beyond `interger` so `long` is needed? Commented Nov 12, 2018 at 7:09