[Techtalk] getting the time as a string in c

Dan dan at cellectivity.com
Thu Sep 29 06:07:47 EST 2005

> I have absolutely no idea what "const struct tm *timeptr" is doing...

I had to search a little in the man pages to find out where you get it,
but I've found it now.

There are two ways (at least!) to represent time in C. The first is with
type "time_t" (a number of seconds; just an integer or long), which is
returned by time(). This is convenient for such things as calculating
how long something took (subtract the end time from the beginning time,
and you have the duration in seconds).

The second way of representing time is with "struct tm", which is broken
down into year, month, day, hour, etc. You get that from localtime(),
which takes a "time_t" and gives you back an equivalent "struct tm".

And, by the way, C doesn't like passing around large chunks of memory
(such a structs), so instead you pass a pointer to the struct you want
to use. That's why you use "const struct foo*" instead of just "foo".

So what you want to do is:

   time_t timeInSeconds;
   const struct tm *timeptr;

   timeInSeconds = time(NULL);
   timeptr = localtime(&timeInSeconds);   /* "&" means "pointer to" */

   /* Note: a second call to localtime() 
    * might overwrite timeptr's memory.
    * that's not a concern here, though.    */
   strftime(timestring, timestrsize, timeformat, timeptr);

   printf("%s\n", timestring);

I hope that helps.    :-)

  The compiler is smarter than you are.
       - Jim Greenly, professor at Georgia Institute of Technology

More information about the Techtalk mailing list