Hi,
I am trying to convert between the RTC registers (in calendar mode) and UTC epoch timestamp, and a bit confused with the results I got so far.
The following my code to set and get RTC calendar time:
// code to set time from time_t baseTime = 1714438861/* GMT: 2024-04-30 01:01:01 */; struct tm* ptm = localtime(&baseTime); RTCCTL1 &= ~RTCBCD; RTCCTL0_H = RTCKEY_H; RTCCTL1 |= RTCHOLD; RTCYEAR = ptm->tm_year + 1970; RTCMON = ptm->tm_mon + 1; RTCDAY = ptm->tm_mday; / RTCDAY = ptm->tm_mday - 1; RTCHOUR = ptm->tm_hour; RTCMIN = ptm->tm_min; RTCSEC = ptm->tm_sec; RTCCTL1 &= ~RTCHOLD; // Code to read RTC time char tsString[24]; sprintf(tsString, "%04d-%02d-%02d %02d:%02d:%02d, ", RTCYEAR, RTCMON, RTCDAY, RTCHOUR, RTCMIN, RTCSEC); /* Output: 2024-05-01 01:01:01 */
When RTC calendar time is immediately read back, the day is one day ahead.
The discrepancy seems originate from how the function localtime() is implemented. With the following test code:
char debugInfo[128]; time_t epochTimeStamp = 325904461 /* 1980-04-30 01:01:01 */; struct tm* ptm = localtime(&epochTimeStamp); sprintf(debugInfo, "tm struct: _year=%d_mon=%d_mday=%d_hour=%d_min=%d_sec=%d\r\n", ptm->tm_year, ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); printDebugInfo(debugInfo, strlen(debugInfo));
I get the following output:
// 41821261, 1971-04-30 01:01:01 tm struct: _year=1_mon=3_mday=30_hour=1_min=1_sec=1 // 957056461: 2000-04-30 01:01:01 tm struct: _year=30_mon=4_mday=1_hour=1_min=1_sec=1 // 325904461: 1980-04-30 01:01:01 tm struct: _year=10_mon=4_mday=1_hour=1_min=1_sec=1 // 168051661: 1975-04-30 01:01:01 tm struct: _year=5_mon=3_mday=30_hour=1_min=1_sec=1 // 294282061: 1979-04-30 01:01:01 tm struct: _year=9_mon=3_mday=30_hour=1_min=1_sec=1 // 320720461, 1980-03-01 01:01:01 tm struct: _year=10_mon=2_mday=2_hour=1_min=1_sec=1
Starting from 1980-03-01, tm_mday seems always 1 day ahead of expected value. Is this some sort of bug in how localtime() is implemented? 1980 was a leap year. I assume the day Feb. 29th is not taken into account by localtime().
Thanks,
ZL