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!
To return the current date and time, use the clock function. Set the output format so that floating-point values display with up to five digits. The sixth element of the date vector output (seconds) is accurate to several digits beyond the decimal point. To round to integer display format, use the fix function.
Use datetime arrays to store date and time information. These arrays support arithmetic, sorting, comparisons, plotting, and formatted display. As of R2022b, serial date numbers and date strings are not recommended for specifying dates and times. Use the datetime , duration , and calendarDuration data types instead.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With