How to convert string to time?

Sorry for the silly question, but could anyone show me how to convert a string, such as, '04:55' to numerical values of hour and minute?
Thank you very much.

 Respuesta aceptada

Paulo Silva
Paulo Silva el 22 de Mzo. de 2011

0 votos

str2num(strrep('04:55',':',''))

1 comentario

Liqing
Liqing el 22 de Mzo. de 2011
Thank you very much. This is a very smart way of handling this.

Iniciar sesión para comentar.

Más respuestas (2)

Matt Tearle
Matt Tearle el 22 de Mzo. de 2011

2 votos

If you want an actual decimal minute value:
x = '04:55'
y = str2double(regexp(x,':','split'))
z = y*[1;1/60]
(Leave off the last line if you just want minutes and seconds as separate array elements.)

1 comentario

Liqing
Liqing el 22 de Mzo. de 2011
It's very nice to see the use of regexp to split the string into two values.
This could be a even better solution.
Thank you very much.

Iniciar sesión para comentar.

Walter Roberson
Walter Roberson el 22 de Mzo. de 2011

0 votos

Is the string fixed width, with a leading 0? If so then,
H = T(1) - '0' * 10 + T(2) - '0';
M = T(4) - '0' * 10 + T(5) - '0';
Or
H = str2num(T(1:2));
M = str2num(T(4:5));
Or
H = [10 1] * (T(1:2)-'0').';
M = [10 1] * (T(4:5)-'0').';

1 comentario

Liqing
Liqing el 22 de Mzo. de 2011
Thank you very much for the reply. This is another way of achieving it.

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 22 de Mzo. de 2011

Community Treasure Hunt

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

Start Hunting!

Translated by