O_O
O_O

Reputation: 4477

MATLAB printing out time as a string

What is the most efficient way to print out time as HH:MM:SS?

I have it set up where my time is x seconds. Then I calculate the hours, minutes, and left over seconds associated with the x seconds.

Then when I want to print it out as a string onto a figure, I do:

sprintf('Time: %d:%d:%d', hours, minutes, seconds);

Unfortunately, this looks ugly as if I have hours or minutes equal to 0, I get something like 0:0:23.

I suppose I can change the hours, minutes, seconds to a string before doing the sprintf. Is there a more efficient MATLAB way though? Thanks!

Upvotes: 12

Views: 13808

Answers (2)

FWDekker
FWDekker

Reputation: 2889

For your goal of formatting a given number of seconds to a nicely formatted string, you should probably use duration, available since MATLAB R2014b:

>> seconds = 5818956;
>> sprintf("Time: %s", duration(0, 0, seconds, Format = "hh:mm:ss"))

ans = 

    "Time: 1616:22:36"

(The two 0 arguments are the number of hours and minutes, respectively.)


There is also the special seconds function to create a duration from only a number of seconds, but then you would need another two lines to set the Format and then print the formatted time.

Upvotes: 1

Anonymous
Anonymous

Reputation: 18631

The best option for date formatting is datestr, for example:

 datestr(now, 'HH:MM:SS')

When it comes to sprintf, then have a look at the formatting parameters. You'll get a better result with zero-padding:

 sprintf('Time: %02d:%02d:%02d', hours, minutes, seconds)

Upvotes: 16

Related Questions