Tuesday, April 10, 2007

Time is everything.

A simple one for you today, but useful none the less.

It involves time. Whether or not it is the fire in which we burn is up for grabs, but you still might want your libc program to be able to output the time!

In a program I wrote this week I did it this way:

#include <time.h>

char* mtime()
{
    static char return[16];
    time_t rawtime;
    struct tm * t;
    time( &rawtime );
    t=localtime( &rawtime );
    snprintf(return,16,"[%02d:%02d%02d]",t->tm_hr,t->tm_min,t->tm_sec);
}

This function returns a string in the format [hr:mn:sc] (hour:minute:second). It will always print two characters for each field, if none are provided it will print zeroes (this is useful as time returns 1 second as 1 not 01, so if you want the string to always be the same length you have to pad it with zeroes).

Time fills the time_t variable called rawtime with the current time since 1970 in seconds. To get something useful to humans we use another function on that returned time. In this case since we want the local time (which also includes the timezone calculation for us) then we call rawtime, which returns a struct* to a tm. I assume it is statically allocated within the localtime function. It may be wise to copy the data out of the struct if you intend to use it much later in your code, but since I use it on the next line, and I haven’t had any problems with it, my code will stay like that until there is a problem :).

Enjoy,

-Crusher4

No comments: