10 years, 6 months ago.

How to set_time() with human reading format?

Well, mbed offers rtc_time.h for set_time(UNIX_TS). That works great.

But I need a function like set_time(year,month,day,hour,min,sec) because of my application's nature. I have to get precise time from CDMA module, which is calibrated by GPS, and then set_time() to system MCU and another GSM module.

I can parse year, month, day, hour, min,sec even microseconds from CDMA, but I have to convert it into UNIX timestamp to use it. How can I convert it?

Question relating to:

2 Answers

10 years, 6 months ago.

Set RTC

void RTCset()  // Set cpu RTC
{    
            t.tm_sec = (seconds);       // 0-59
            t.tm_min = (minute);        // 0-59
            t.tm_hour = (hour);         // 0-23
            t.tm_mday = (dayofmonth);   // 1-31
            t.tm_mon = (month-1);       // 0-11  "0" = Jan, -1 added for Mbed RCT clock format
            t.tm_year = ((year)+100);   // year since 1900,  current year + 100 + 1900 = correct year
            set_time(mktime(&t));       // set RTC clock                                 
}

Accepted Answer

Thanks, Paul & Erik,

Actually I have referenced some C++ code and have some hands on labs on my STM32F103RB board this morning.

_tm.tm_year = 2015-1900; _tm.tm_mon = 5; _tm.tm_mday = 6; _tm.tm_hour = 11; _tm.tm_min = 30; _tm.tm_sec = 15; _tm.tm_isdst = 0; _tm.tm_yday = 0; set_time(mktime(&_tm)); time_t second = time(NULL); term.printf("Time - %s\r\n", ctime(&second));

1) Result -> Time - Sat Jun 6 11:30:15 2015 (OK)

However, from the very beginning, I have tried zero on every member of _tm. The result is wired.

2) Result -> Time - Wed Feb 6 06:28:16 2036 (Bad)

Then I tried to set year to "2015-1900", others are still zero. I got this:

3) Result -> Time - Wed Dec 31 00:00:00 2014 (Bad)

The internal converter thinks 2015-0-0,00:00:00 as 2014/12/31, 00:00:00.

Very interesting !

However, mktime() works now.

posted by Kai Liu 18 Jun 2015
10 years, 6 months ago.

With mktime: http://www.cplusplus.com/reference/ctime/mktime/