/**
* @author: FlyyingPiggy2020
* @data: 2022-09-08 09:33:10
* @last_author: FlyyingPiggy2020 154562451@qq.com
* @last_time: 2022-09-08 16:26:32
* @brief: 和应用代码无关的函数,用于数学计算等。
* @copyright: copyright(c) 2022 by FlyyingPiggy2020, All Rights Reserved.
*/
#include "fp.h"
#include "fp_user_lib.h"
/**
* [url=home.php?mod=space&uid=247401]@brief[/url] 获取从1970年1月1日0时0分0秒至今的秒数
* @param {tm} tm_now
* [url=home.php?mod=space&uid=266161]@return[/url] {*}
*/
uint32_t fp_mktime(tm_t tm_now)
{
uint16_t year = tm_now.tm_year;
int16_t mon = tm_now.tm_mon;
uint16_t day = tm_now.tm_mday;
uint16_t hour = tm_now.tm_hour;
uint16_t min = tm_now.tm_min;
uint16_t sec = tm_now.tm_sec;
mon = mon - 2;
if ( mon <= 0)
{
mon += 12;
year -= 1;
}
return (((
(uint32_t) (year/4 - year/100 + year/400 + 367*mon/12 + day) +
year*365 - 719499
)*24 + hour /* now have hours */
)*60 + min /* now have minutes */
)*60 + sec; /* finally seconds */
};
/**
* @brief 从1970年1月1日0时0分0秒至今的秒数 转换成 年月日 具体格式参考 struct tm
* @param {tm} tm_time {uint32_t} timestamp
* @return {*}
*/
void fp_gmtime(struct tm *tm_time, uint32_t timestamp)
{
uint16_t four_year_num; /* 有多少个四年 */
uint16_t one_year_hours;/* 一年的小时数 */
const static uint8_t days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};/* 非闰年每月天数 */
const static uint16_t ONE_YEAR_HOURS = 8760; /* 非闰年的小时数 365 * 24 */
const static uint16_t FOUR_YEAR_HOURS = 35064;/* 四年的小时数(365 * 3 + 366)* 24 */
if (timestamp >= 0X7FFFFFFF)
{
return;
}
tm_time->tm_isdst = 0;
tm_time->tm_sec = (int32_t)(timestamp % 60); /* 秒 */
timestamp /= 60;
tm_time->tm_min = (int32_t)(timestamp % 60); /* 分 */
timestamp /= 60;
tm_time->tm_wday = (int32_t)(timestamp/24 + 4) % 7; /* 计算星期 1970年1月1日是星期四 */
four_year_num = timestamp / FOUR_YEAR_HOURS;
tm_time->tm_year = (four_year_num << 2) + 1970; /* 计算年 */
timestamp %= FOUR_YEAR_HOURS; /* 不足四年的小时数 */
while(1)
{
one_year_hours = ONE_YEAR_HOURS;
if ((tm_time->tm_year & 3) == 0)
{
one_year_hours += 24;
}
if (timestamp < one_year_hours)
{
break;
}
tm_time->tm_year++;
timestamp -= one_year_hours;
}
tm_time->tm_hour = (int32_t)(timestamp % 24); /* 计算时 */
timestamp /= 24; /* 一年中剩下的天数 */
timestamp++;
tm_time->tm_yday = timestamp - 1; /* 计算天 */
if ((tm_time->tm_year & 3) == 0)
{
if (timestamp > 60)
{
timestamp--;
}
else if (timestamp == 60)
{
tm_time->tm_mon = 1;
tm_time->tm_mday = 29;
return;
}
}
for (tm_time->tm_mon = 0; days[tm_time->tm_mon] < timestamp; tm_time->tm_mon++)
{
timestamp -= days[tm_time->tm_mon];
}
tm_time->tm_mon++;
tm_time->tm_yday++;
tm_time->tm_mday = (int32_t)(timestamp);
}
/* 测试例程 */
void fp_time_test_demo(void)
{
tm_t tm_now,tm_test;
uint32_t time;
tm_now.tm_year = 2022;
tm_now.tm_mon = 9;
tm_now.tm_mday = 8;
tm_now.tm_hour = 15;
tm_now.tm_min = 12;
tm_now.tm_sec = 0;
time = fp_mktime(tm_now);
fp_gmtime(&tm_test,time);
}
|