• C

a function to convert HH:MM:SS to number of seconds?

Does anyone know of or have a function that can read in a string of the form HH:MM:SS.DD (e.g., 14:23:09.21, "14 hours, 23 minutes, 9.21 seconds) and convert it to a number of seconds?
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:

long tcon(ts)
char *ts;

{   int hrs,min,sec,secf;

sscanf(times,"%d:%d:%d.%d",&hrs,&min,&sec,&secf);
tsec=(long)hrs*3600+min*60+sec;
return(tsec);
}

or if you need the fractional result:

float tcon(ts)
char *ts;

{   int hrs,min,sec,secf;
;

sscanf(times,"%d:%d:%d.%d",&hrs,&min,&sec,&secf);
tsec=(long)hrs*3600+min*60+sec;
return((float)tsec+((float)secf)/100);
}
0

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Commented:
Sorry, note you need a declaration of:

long tsec;

in both of those functions.
The second one might look better as:

float tcon(ts)
char *ts;

{   int hrs,min,sec,secf;
float tsec;

sscanf(times,"%d:%d:%d.%d",&hrs,&min,&sec,&secf);
tsec=(float)((long)hrs*3600+min*60+sec)+((float)secf)/100;
return(tsec);
}

Or, if the number of decimals on the seconds is variable you would need to read the seconds as a float:

float tcon(ts)
char *ts;

{   int hrs,min;
float sec,tsec;

sscanf(times,"%d:%d:%f",&hrs,&min,&sec);
tsec=(float)((long)hrs*3600+min*60+sec)+secf;
return(tsec);
}

Perhaps that is better all around.
0
Commented:
Is there something you needed further clarification for, before you graded the answer?
0
Author Commented:
Nope, I just hadn't had a chance to look at it yet. Just implemented it, and it works great. Thanks!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.