Using time.h C Library Functions

In an MCU system, the firmware usually can keep time using either the MCU’s built-in or an external RTC (Real Time Clock). System connected to the internet can get time from one of the NTP servers. Each RTC has its own format of storing time.


Often it is convenient to display time, or to calculate lapsed time etc. The C library provides a rich set of functions for dealing with time. Here’s an excerpt of some of the functions declared in time.h


char *asctime(const struct tm *tm);

char *ctime(const time_t *timep);

struct tm *gmtime(const time_t *timep);

struct tm *localtime(const time_t *timep);

double difftime(time_t time1, time_t time0);


time_t mktime(struct tm *tm);


A web search will describe the semantics of the time.h functions in full. Two data types are referenced struct tm and time_t, both of which are described below. asctime and ctime return a string based on the input argument.


The starting point is to convert a time value from the RTC internal format to the C library’s time_t representation. time_t is an alias to a C fundamental type (usually a 32-bits int) that represents the number of seconds since Jan 1, 00:00 1970, known as the Unix Epoch Time. As it is a signed integer, this does mean that the time will roll over on Jan 19, 2038.


To converting to a time_t value, you can use the function mktime. This function takes a structure pointer (struct tm *) and produces an equivalent time_t value. struct tm looks like this:


struct tm {
    int tm_sec;         /* seconds */
    int tm_min;         /* minutes */
    int tm_hour;        /* hours */
    int tm_mday;        /* day of the month */
    int tm_mon;         /* month */
    int tm_year;        /* year */
    int tm_wday;        /* day of the week */
    int tm_yday;        /* day in the year */
    int tm_isdst;       /* daylight saving time */

For the purpose of mktime, the fields tm_wday, tm_yday are ignored. For example, let’s say the RTC time is July 28, 2018 4:04 AM. You could write:


#include <time.h>

struct tm rtc_time;

time_t time;


rtc_time.tm_year = 2018;

rtc_time.tm_mon = 7;

rtc_time.tm_mday = 28;

rtc_time.tm_hour = 4;

rtc_time.tm_min = 4;


time = mktime(&rtc_time);


Once you have the time in time_t form, then you can use asctime to print it out, etc.