Skip to content

create your own time stamp

If you wanna create a time stamp that display date and time, you can simply uses asctime() and localtime(), time() and a time_t variable to do that. time_t will declare a variable to store calendar time.

Calendar time, an absolute time value, it represents the number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC).

time() will returns the current calendar time to store at time_t variable. Next we uses localtime() to extract info from calendar time and store into a time structure (struct tm). At last asctime() takes in the time structure and turns the entire thing into string.

It is more easy to understand through example,

void timestamp()
{
    time_t ltime; /* calendar time */
    ltime=time(NULL); /* get current cal time */
    printf("%s",asctime( localtime(&ltime) ) );
}

This will print out :

Sat Jan 27 10:32:12 2007

If you want to customize the time stamp, you have to do more work, you need to adjusting calendar time value from the time structure before you print out.

Lets me redefine the timestamp()

int timestamp()
{
    time_t ltime;
    struct tm *Tm;

    ltime=time(NULL);
    Tm=localtime(&ltime);

    printf("[%d] %d %d %d, %d:%d:%d",
            Tm->tm_wday, /* Mon - Sun */
            Tm->tm_mday,
            Tm->tm_mon,
            Tm->tm_year,
            Tm->tm_hour,
            Tm->tm_min,
            Tm->tm_sec);
}

The result seems to be not what we are looking for,

[6] 27 0 107, 10:32:12

[6] means Saturday, that is Day of the Week.
27 0 107, its calendar time, so you need to adjust it.

    printf("[%d] %d %d %d, %d:%d:%d",
            Tm->tm_wday, /* Mon - Sun */
            Tm->tm_mday,
            Tm->tm_mon+1,
            Tm->tm_year+1900,
            Tm->tm_hour,
            Tm->tm_min,
            Tm->tm_sec);

You need milliseconds and microseconds too? The method of getting it is platform dependent, for win32, you may check out struct timeb and ftime(). For unix based system, let stake a look at gettimeofday() and struct timeval.

   struct timeval detail_time;
   gettimeofday(&detail_time,NULL);
   printf("%d %d",
   detail_time.tv_usec /1000,  /* milliseconds */
   detail_time.tv_usec); /* microseconds */

For gettimeofday(), you need to include sys/time.h header.

Categories: Uncategorized.

Comment Feed

5 Responses

  1. Good Article

    puneetMay 29, 2007 @ 8:40 pm
  2. Really helpful. Thank you very much.

  3. Good Tut. Easy to understand



Some HTML is OK

or, reply to this post via trackback.

Continuing the Discussion

  1. [...] create your own time stamp [...]

  2. [...] my previous post, create your own time stamp 2, I have introduced a way to construct your own time [...]