测试记录
对比网站
补充说明:这个网站转时间戳有点坑!
https://tool.lu/timestamp/
源文件
const uint8_t uDaysPerMonth[13]= { 0,31,28,31,30,31,30 ,
31,31,30,31,30,31
};
uint32_t RTC_DecodeSec(DATE_STRUCT* pdate , int32_t offset )
{
uint32_t Seconds;
uint16_t uYear,usYear ;
uint8_t uMonth;
uint8_t feb_days = 28 ;
Seconds = 0;
usYear = (uint16_t)pdate->year + BEGIN_YEAR ;
for(uYear = BEGIN_YEAR; uYear < usYear; uYear++)
{
Seconds += (uint32_t)DAYS_PER_YEAR(uYear)*SECONDS_PER_DAY;
}
if(IS_LEAPYEAR(uYear))
feb_days = 29 ;
for(uMonth = 1; uMonth < pdate->month; uMonth++)
{
if(uMonth == 2)
{
Seconds += (uint32_t)((uint32_t)feb_days * SECONDS_PER_DAY) ;
} else
{
Seconds += (uint32_t)((uint32_t)uDaysPerMonth[uMonth]*SECONDS_PER_DAY);
}
}
Seconds += (uint32_t)(((uint32_t)pdate->day-1)*SECONDS_PER_DAY);
Seconds += (uint32_t)((uint32_t)pdate->hour*(uint32_t)3600);
Seconds += (uint32_t)((uint32_t)pdate->min*60);
Seconds += (uint32_t)((uint32_t)pdate->sec);
{
Seconds += offset ;
}
return (Seconds);
}
头文件
#define BEGIN_YEAR 1970
#define SECONDS_PER_DAY 86400
#define IS_LEAPYEAR(y) (((0 == (y) % 4) && (0 != (y) % 100)) || (0 == (y) % 400))
#define DAYS_PER_YEAR(y) (IS_LEAPYEAR(y)? 366 : 365)
typedef struct
{
uint8_t min;
uint8_t hour;
uint8_t day;
uint8_t month;
uint8_t year;
uint8_t sec;
} DATE_STRUCT;
补充
第二种实现方法
#define MINUTE 60
#define HOUR (60*MINUTE)
#define DAY (24*HOUR)
#define YEAR (365*DAY)
/* interestingly, we assume leap-years */
static int month[12] = {
0,
DAY*(31),
DAY*(31+29),
DAY*(31+29+31),
DAY*(31+29+31+30),
DAY*(31+29+31+30+31),
DAY*(31+29+31+30+31+30),
DAY*(31+29+31+30+31+30+31),
DAY*(31+29+31+30+31+30+31+31),
DAY*(31+29+31+30+31+30+31+31+30),
DAY*(31+29+31+30+31+30+31+31+30+31),
DAY*(31+29+31+30+31+30+31+31+30+31+30)
};
struct tm
{
uint32_t tm_sec; // seconds after the minute - [0, 60] including leap second
uint32_t tm_min; // minutes after the hour - [0, 59]
uint32_t tm_hour; // hours since midnight - [0, 23]
uint32_t tm_mday; // day of the month - [1, 31]
uint32_t tm_mon; // months since January - [0, 11]
uint32_t tm_year; // years since 1900
};
uint32_t kernel_mktime(struct tm * tm)
{
uint32_t res;
uint32_t year;
year = tm->tm_year - 70;
/* magic offsets (y+1) needed to get leapyears right.*/
res = YEAR*year + DAY*((year+1)/4);
res += month[tm->tm_mon];
/* and (y+2) here. If it wasn't a leap-year, we have to adjust */
if (tm->tm_mon>1 && ((year+2)%4))
res -= DAY;
res += DAY*(tm->tm_mday-1);
res += HOUR*tm->tm_hour;
res += MINUTE*tm->tm_min;
res += tm->tm_sec;
return res;
}