Data Type for time_t

18 Dec 2013

Hi:

I would like to find out the documentation for mktime() function used by mbed.

According to http://www.cplusplus.com/reference/ctime/mktime/, mktime() returns -1 if it could not convert broken down time to seconds. E.g., 31st Feb 2013.

    struct tm  Clock;
    Clock.tm_year = 2013;
    Clock.tm_mon = 1;
    Clock tm_mday = 31;

    time_t sec = mktime(&Clock);
    if (sec == -1)
        printf("Error in clock setting\n");
    else
        set_time(sec);

Could not work as time_t is an unsigned value from the error message. Any comment? Thank

21 Dec 2013

There is a bug in libc library by Keil if mbed uses MDK.

Can anyone try gcc?

#include "mbed.h"

DigitalOut myled(LED1);

void SetDateTime
(int           year = 2013
,int           mon = 0
,int           day = 1
,int           hour = 0
,int           min = 0
,int           sec = 0
)
{
    struct     tm Clock;
    Clock.tm_year = year - 1900;
    Clock.tm_mon  = mon;
    Clock.tm_mday = day;
    Clock.tm_hour = hour;
    Clock.tm_min  = min;
    Clock.tm_sec  = sec;
    time_t epoch = mktime(&Clock);
    if (epoch == (time_t) -1) {
        error("Error in clock setting\n");
        // Stop here
    }
    set_time(epoch);
}

void ShowDateTime()
{
    char       str[32];
    time_t     seconds = time(NULL);
    struct tm *tminfo = localtime(&seconds);

    strftime(str, 32, "%F,%T", tminfo);
    printf("RTC: %s\n", str);
}

int main()
{
    SetDateTime(2013,0,1,0,0,0); // 2013-1-1 00:00:00
    ShowDateTime();
    SetDateTime(2014,0,32,0,0,0); // 2014-1-32 00:00:00 which is invalid.
    ShowDateTime();

    while(1) {
        myled = 1;
        wait(0.5);
        myled = 0;
        wait(0.5);
        ShowDateTime();
    }
}

The outputs:

RTC: 2013-01-01,00:00:00
RTC: 2014-02-01,00:00:00
RTC: 2014-02-01,00:00:01
14 Sep 2014

I came across this post when I am looking for documentation of mktime. So thanks for the demonstration on how to use mktime function.

For your reference, the result from LPCXpresso is the same:

RTC: 2013-01-01,00:00:00

RTC: 2014-02-01,00:00:00 ( I assume this is the bug you meant)

RTC: 2014-02-01,00:00:01

This was compiled in LPCXpresso 7.1( I assume LPCXpresso uses GCC, at least some non-keil compiler). Strange enough, the code size out of LPCXpresso for this application is as big as 45,420B, while code size out of mbed compiler is only 20kb or so.