请注意,本文内容源自机器翻译,可能存在语法或其它翻译错误,仅供参考。如需获取准确内容,请参阅链接中的英语原文或自行翻译。
器件型号:MSP430F6723 您好!
我正在尝试在 RTC 寄存器(在日历模式下)和 UTC epoch 时间戳之间进行转换、到 目前为止结果有点困惑。
我的以下代码用于设置和获取 RTC 日历时间:
// 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 */
如果立即读回 RTC 日历时间、则提前一天。
差异 似乎源于函数 localtime()的实现方式。 测试代码如下:
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));
我得到以下输出:
// 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
从1980年03月01日 开始、tm_mday 似乎始终比预期值提前1天。 这是在如何实现 localtime()中的某种错误吗? 1980年 是一个飞跃年。 我认为2月29日是不考虑通过本地时间()。
谢谢。
ZL