# Calculate hours elapsed from 2 times

17 views (last 30 days)
Milou on 25 Jul 2012
Hello,
I have a cell array with two columns. It looks like the following:
thetime = ['9:30PM' , '12:30pm', '11:30am' ; '8:00am', '6-6:30am', '7:20am']
I want to find out how many hours have passed from items in column 1 to those in column 2 (same row).
Before subtracting starting time from ending time, I have tried to convert am/pm times to 24hour-time using:
but this returns: Cannot convert input into specified date string. DATENUM failed.
I have also tried:
but this returns a 1x1 cell with the number 7.3487e+05
What am I doing wrong? Any ideas as to what I can try instead?
Thank you so much for your time and help!

Sumit Tandon on 25 Jul 2012
Try using the DATEVEC command to find difference between two dates/times.
For example:
>> a = datevec('9:30 PM');
>> b = datevec('9:40 PM');
>> b-a
ans =
0 0 0 0 10 0
DATENUM converts date information to serial date format.
Milou on 25 Jul 2012
also, i just realized that your example above shows:
9:40pm - 9:30pm = 10.
I want a function that calculates the time elapsed between those times, ie. 12 hours.
Is there any way to do this?

Star Strider on 25 Jul 2012
See the ‘etime’ function.
Example:
thetime = {'9:30PM' , '12:30pm', '11:30am' ; '8:00am', '6-6:30am', '7:20am'}'
time2 = datevec(thetime(1,:), 16)
Td_s = etime(time2(1,:),time2(2,:)) % Elapsed time in seconds
Td_h = Td_s/3600 % Elapsed time in hours
The ‘16’ is a predefined time format. See ‘Numeric Identifiers for Predefined Formats’ about half way down the ‘Date and Time Functions’ page: http://www.mathworks.com/help/techdoc/matlab_prog/bspgcx2-1.html
Star Strider on 26 Jul 2012
After stopping GlobalSearch (after 18 hours without results) I ran the code I gave you with ‘6-6:30pm’ changed to ‘6:30pm’. After changing this line to guarantee a column vector:
Td_h(k1,:) = Td_s/3600;
got this output:
Td_h =
13.5000e+000
6.0000e+000
4.1667e+000