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?
djc2Asked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
imladrisConnect With a Mentor Commented:
How about:

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
 
imladrisCommented:
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
 
imladrisCommented:
Is there something you needed further clarification for, before you graded the answer?
0
 
djc2Author Commented:
Nope, I just hadn't had a chance to look at it yet. Just implemented it, and it works great. Thanks!
0
All Courses

From novice to tech pro — start learning today.