I was wondering whether there is a function in C that takes time in the following format (current date and time in seconds are in Epoch format)
a.1343323725
b.1343326383
And returns me the result as difference between the two time as hrs:mins:secs
Sorry for any confusion, to clarify my point I wrote a code that gets that gets the user’s current time execute some block of code and gets the time again. And I was wondering whether the difference could be converted into hrs:mins:sec as a string literal.
#include <sys/time.h>
#include <stdio.h>
int main(void)
{
struct timeval tv = {0};
gettimeofday(&tv, NULL);
printf("%ld \n", tv.tv_sec);
//Execte some code
gettimeofday(&tv, NULL);
return 0;
}
First you want to get the time difference in seconds out of the timeval structures that those functions return, using something like this:
Where a and b were the values returned by gettimeofday.
Next you want to break that down into units of hours, minutes and seconds.
Finally we want to get that data into a string, using the snprintf function from
sprintf words exactly like printf, except the output goes into a string, not onto stdout, and snprintf is the same except it won’t write more than n characters into the string, to prevent buffer overflows.
Stitch those together and you’ve got the job done.