how to find time difference between 2 times , in milliseconds.

So I have a cell with a column with data like this :
.....
'18:42:45.813'
'18:42:46.028'
'18:42:46.139'
'18:42:46.359'
'18:42:46.463'
'18:43:06.558'
'18:43:06.779'
....
I want to find out the time differences lets say between 2 rows,
I tried it like this: etime(datevec(datenum(c{1,2}{1,1})), datevec(datenum(c{1,2}{2,1})))
it worked great when I did not have milliseconds, my data was like this:
.....
'18:42:25'
'18:42:36'
'18:42:46'
....
but if I add data with milliseconds it gives me a wrong answer.
I want the result in milliseconds (also in seconds if possible).

 Accepted Answer

Just work with duration format.
t={'18:42:45.813'
'18:42:46.028'
'18:42:46.139'
'18:42:46.359'
'18:42:46.463'
'18:43:06.558'
'18:43:06.779'};
td = duration(t,'inputformat','hh:mm:ss.SSS');
out = milliseconds(diff(td))
ans =
215
111
220
104
20095
221
The only problem is if your time is displaying time of day, in which case you need to use datetime instead, or else you will get a large spike in your time difference at midnight.

10 Comments

I see, and how would I go about finding out the diff between let`s say the first and the fifth element only
If you are looking for that specifically, then
milliseconds(td(5)-td(1))
If you are looking for the "time from the start", then
milliseconds(td-td(1))
Yes , that is exactly what I wanted , thank you sir!
Follow up question: my data is in a 1x3 cell , and in {1,2} is my time column located, the td gives me an error:
"Input data must be a numeric matrix with three columns, or three separate numeric arrays."
I'm not sure what function you used to get that error message. duration? Perhaps you are using an older version of matlab?
Okay, turns out they added the cell array input type in 2018a, while 2017b only accepts arrays. That's unfortunate, but here's a workaround
[~,~,~,hh,mm,ss] = datevec(t,'HH:MM:SS.FFF')
td = duration(hh,mm,ss);
it`s working, but with this new method how to I calculate diff between two times? not consecutive, let`s say td(1) and td(6) ?
Nvm , I just use milliseconds (td(5) - td(1)) :) thank you so much , you helped me out a lot.
In earlier versions, you can convert from text to duration using datevec, or using datetime+timeofday, but perhaps even easier, you can use text2duration on the FEX.

Sign in to comment.

More Answers (1)

Categories

Asked:

on 23 Oct 2018

Commented:

on 31 Oct 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!