Function to calculate seconds between times in hh:mm:ss string format

I want to create a function that takes two strings as inputs, tref and t, and computes and returns the number of seconds until t since tref. Both tref and t are strings in the format hh:mm:ss.
For example
function_name('20:00:00','22:53:44')
should return
10424
And for simplicity, I want to require that hour, minute, and second values in t are greater than or equal to hour, minute, and second values in tref, respectively. Is there any way to do this without any built in matlab time/date functions?

 Risposta accettata

What if you can get by without your requirement for simplicity?
function ts = timediff(tref, t)
tref = dot([3600 60 1], str2double(regexp(tref, ':', 'split')));
t = dot([3600 60 1], str2double(regexp(t, ':', 'split')));
if t > tref
ts = t - tref;
else
error('t must be later than tref')
end
end
>> timediff('20:00:00','22:53:44')
ans =
10424
>> timediff('23:00:00','22:53:44')
Error using timediff (line 7)
t must be later than tref
You'll have to check the inputs more carefully and deal with any innappropriate values. e.g.
>> timediff('23:00','22:53:44')
Error using dot
A and B must be same size.
Error in timediff (line 2)
tref = dot([3600 60 1], str2double(regexp(tref, ':', 'split')));

3 Commenti

This is exactly what I needed, thank you so much for your help!
Using sscanf is simpler and much more efficient than regexp and str2double:
>> [3600,60,1]*sscanf('22:53:44','%f:') - [3600,60,1]*sscanf('20:00:00','%f:')
ans =
10424
Nice, thank you for the tip!

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su MATLAB in Centro assistenza e File Exchange

Richiesto:

il 20 Apr 2020

Commentato:

il 21 Apr 2020

Community Treasure Hunt

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

Start Hunting!

Translated by