Getting the System Time in C (Function)

It has been a while since I’ve posted a tutorial, so I figured I would go over a simple example on how to write a function to return the system time in C.

The code below has only been tested on a handful of UNIX systems (RHEL 6.5, SLES 10 and Solaris 10), therefore I can’t guarantee the output on Windows systems (but it really should, considering time.h is a part of the Standard C library).

Overall, it is really straightforward and mostly self-explanatory if you’re at all familiar with C, and my solution is partially borrowed from a post on StackOverflow (with a few enhancements).

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

const char * getSystemTime()
{
    struct timeval tp;
    struct tm *t;
    char *current_time;
    time_t curtime;    
    
    gettimeofday(&tp, 0); //Pass tp to library function gettimeofday()
    curtime = tp.tv_sec;
    t = localtime(&curtime);
    
    current_time = (char *) malloc(sizeof(char) * 18);
    sprintf(current_time,"%02d:%02d:%02d:%04d", 
                         t->tm_hour, t->tm_min, t->tm_sec, tp.tv_usec/1000);
    return current_time;
}

int main (void)
{
    printf("%s\n", getSystemTime());
}

 

The time format is important to note here:

"%02d:%02d:%02d:%04d", t->tm_hour, t->tm_min, t->tm_sec, tp.tv_usec/1000

This essentially translates to the following time format:

12:51:12:0491 | | | |-> Milliseconds (4 digits) | | |----> Seconds (2 digits) | |-------> Minutes (2 digits) |----------> Hours (2 digits)

For more info the time.h library in C, check out the links below:
GNU: Elapsed Time
cplusplus.com: C Library time.h
cplusplus.com: C Library struct tm

system-time-C