File Exchange

## Seconds to hours, minutes, seconds

version 1.4.0.0 (1.48 KB) by Simon Robinson

### Simon Robinson (view profile)

Converts a time in seconds to a time in hours, minutes and seconds.

Updated 02 Feb 2009

A very simple program to convert a time in seconds to a string giving the time in hours, minutes and seconds. Useful for producing readable toc output from programs which run for ages.

e.g.

help secs2hms
SECS2HMS - converts a time in seconds to a string giving the time in hours, minutes and second
Usage TIMESTRING = SECS2HMS(TIME)]);
Example 1: >> secs2hms(7261)
>> ans = 2 hours, 1 min, 1.0 sec
Example 2: >> tic; pause(61); disp(['program took ' secs2hms(toc)]);
>> program took 1 min, 1.0 secs

Rob Campbell

### Rob Campbell (view profile)

Comments regarding datestr are relevant, as this is more simple and idiomatic, but these snippets produce different output to what the author is apparently trying to generate here. Nonetheless, the author's code isn't very idiomatic. Something that is more so and would still produce the desired output is:

[~,~,~,H,M,S] = datevec(timeInSeconds / (24*60^2) );
time='';
if H > 0
time = sprintf('%s %d hrs', time, H);
end

if M > 0
time = sprintf('%s %d min', time, M);
end

if H==0 && S > 0
time = sprintf('%s %d sec', time, S);
end

Bulk Masx

pankaj singh

### pankaj singh (view profile)

VERY COOL CODE FOR CODES TAKING VERY LONG TIME TO RUNS.....

Pete

### Pete (view profile)

I think much the same could be done with:

nSecs = 90;
datestr(nSecs/86400, 'HH:MM:SS.FFF')

Thorbjorn

### Thorbjorn (view profile)

Nice! This is useful for extended numerical calculations/ simulaitons. I have developed a similar function a while ago that I find useful (even simpler, but also faster than yours) -- will post it on the web.

Jos (10584)

### Jos (10584) (view profile)

should read: _NO_ H1 line ...

Jos (10584)

### Jos (10584) (view profile)

This file contains H1 line , no help section and no comments, which makes it rather useless. First, how will you find the name of this file in the future if you cannot use LOOKFOR. Secondly, even if you find it, how will you know how to use it, if you cannot use HELP. Third, the total lack of comments makes it difficult to decipher what an end-user should do. In other words, it is only useful to someone with some matlab skills already. On the other hand, she or he will probably stick to something more matlab-ish like:

TimeInSecs = 7261 ;
disp(datestr(datenum(0,0,0,0,0,TimeInSecs),'HH:MM:SS'))

Husam Aldahiyat

### Husam Aldahiyat (view profile)

Name is too long; have to manually change it to s2hms.
Other than that, pretty cool code.

 2 Feb 2009 1.4.0.0 Function name shortened. H1 line and help added.
##### MATLAB Release Compatibility
Created with R2007b
Compatible with any release
##### Platform Compatibility
Windows macOS Linux