项目场景:
RTC获取时间后,需要转换成时间戳
问题描述
一开始百度了很多时间转时间戳,但是都没发现能直接用的。这边写下来,方便以后过来看。
解决方案:
#include "time.h" //系统头文件
void RTC_TimeShow(void)
{
RTC_TimeType RTC_TimeStructure;
RTC_DateType RTC_DateStructure;
struct tm local_time;
/* Get the current Time and Date */
RTC_GetDate(RTC_FORMAT_BIN, &RTC_DateStructure);
RTC_GetTime(RTC_FORMAT_BIN, &RTC_TimeStructure);
/*调用系统的时间结构体,并填充数据 */
local_time.tm_year =RTC_DateStructure.Year+2000-1900; // 注意:这边加上2000是因为我读出来的年是22,
// 不是2022。后面减去1900,是看到调用mktime接口必须要减的。
// 原因你们可以自己查一下
local_time.tm_mon = RTC_DateStructure.Month-1; //月份要减一,这个你可以自己验证下不减,时间戳转换出来会多一个月
local_time.tm_mday = RTC_DateStructure.Date;
local_time.tm_hour = RTC_TimeStructure.Hours-8; //这个好像是因为时区的原因
local_time.tm_min = RTC_TimeStructure.Minutes;
local_time.tm_sec = RTC_TimeStructure.Seconds;
logshellyellow("TimeStamp %d",mktime(&local_time));
logshellyellow("Time : %0.2d-%0.2d-%0.2d %0.2d:%0.2d:%0.2d ",
RTC_DateStructure.Year,
RTC_DateStructure.Month,
RTC_DateStructure.Date,
RTC_TimeStructure.Hours,
RTC_TimeStructure.Minutes,
RTC_TimeStructure.Seconds);
/* Unfreeze the RTC DAT Register */
(void)RTC->DATE;
}