# Duration in double between two datenum

10 visualizaciones (últimos 30 días)
Luis Ruiz el 7 de Sept. de 2018
Comentada: Peter Perkins el 12 de Sept. de 2018
I have two dates given in text format, I want to have the real duration in seconds between the two values.
The answer is -24, and I can do it parsing the strings. But does MATLAB have a function to do it nice and quick?
If I do the following the answer is not a -24 that I can use as a double:
datenum('2018-09-07 18:36:05.079')-datenum('2018-09-07 18:36:29.079')
I need this time for a Simulink simulation. For example, I might need the duration in seconds between two days.
##### 2 comentariosMostrar NingunoOcultar Ninguno
Stephen23 el 7 de Sept. de 2018
Luis Ruiz el 10 de Sept. de 2018
I edited my question to match the answers.

Iniciar sesión para comentar.

Stephen23 el 7 de Sept. de 2018
Editada: Stephen23 el 7 de Sept. de 2018
To get seconds simply multiply the days by 60*60*24:
>> F = 'yyyy-mm-dd HH:MM:SS.FFF';
>> D = datenum('2018-09-07 18:36:05.079',F)-datenum('2018-09-07 18:36:29.079',F);
>> D*60*60*24
ans = -24.000
##### 2 comentariosMostrar NingunoOcultar Ninguno
Luis Ruiz el 10 de Sept. de 2018
Editada: Luis Ruiz el 10 de Sept. de 2018
This one seems to be the right answer, but then, does it mean that operations between two datenum values are always in days?
Stephen23 el 10 de Sept. de 2018
@Luis Ruiz: yes, datenum always returns days. But the conversion to seconds is trivial, as my answer shows.

Iniciar sesión para comentar.

### Más respuestas (2)

Peter Perkins el 7 de Sept. de 2018
If possible, don't use datenum. Use datetimes:
>> fmt = 'yyyy-MM-dd HH:mm:ss.SSS';
>> dur = datetime('2018-09-07 18:36:05.079','Format',fmt) - datetime('2018-09-07 18:36:29.079','Format',fmt)
dur =
duration
-00:00:24
>> dur.Format = 's'
dur =
duration
-24 sec
##### 3 comentariosMostrar 1 comentario más antiguoOcultar 1 comentario más antiguo
James Tursa el 7 de Sept. de 2018
To turn it into a double, e.g.
seconds(dur)
Peter Perkins el 12 de Sept. de 2018
As James says, you can convert, but the point of duration is that you may not need a number. duration supports all kinds of time arithmetic. Hard to know if that's possible in your case.

Iniciar sesión para comentar.

Image Analyst el 7 de Sept. de 2018
Editada: Image Analyst el 10 de Sept. de 2018
Try the etime() function.
t1 = datevec('2018-09-08 18:36:05.079','yyyy-mm-dd HH:MM:SS.FFF')
t2 = datevec('2018-09-07 18:36:29.079','yyyy-mm-dd HH:MM:SS.FFF')
elapsedTime = etime(t1, t2) % Results in seconds.
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

### Categorías

Más información sobre Dates and Time en Help Center y File Exchange.

R2018a

### Community Treasure Hunt

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

Start Hunting!

Translated by