Epoch时间转换为datetime_t结构各字段值的实现方法求助
解决方案
方法1:使用C标准库实现(推荐)
直接用标准库<time.h>中的gmtime()函数即可完成转换,无需手动处理闰年、月份天数等复杂逻辑,该函数会将time_t类型的Epoch时间戳转换为struct tm结构体,字段映射规则如下:
struct tm.tm_year为从1900年开始计算的年偏移量,加1900即可得到结构体要求的公元年份struct tm.tm_mon范围为011(0代表1月),加1即可得到112格式的月份struct tm.tm_mday范围为1~31,直接对应日期字段struct tm.tm_wday范围为0~6(0代表周日),和datetime_t的dotw字段要求完全一致,可直接赋值- 时分秒也可以直接从
struct tm对应字段获取,不需要手动计算
示例代码:
#include <time.h> void epoch_to_datetime(time_t epochTime, datetime_t *dt) { // 如果时间戳是本地时区的,将gmtime替换为localtime即可 struct tm *utc_time = gmtime(&epochTime); dt->year = utc_time->tm_year + 1900; dt->month = utc_time->tm_mon + 1; dt->day = utc_time->tm_mday; dt->dotw = utc_time->tm_wday; dt->hour = utc_time->tm_hour; dt->min = utc_time->tm_min; dt->sec = utc_time->tm_sec; }
方法2:手动实现转换逻辑
如果需要脱离标准库自行实现,核心逻辑如下:
- 先计算从1970年1月1日到目标时间的总天数:
total_days = epochTime / 86400 - 星期计算:1970年1月1日为周四(对应
dotw值为4),因此dotw = (total_days + 4) % 7,刚好符合0代表周日的规则 - 逐年减去对应年份的天数(闰年366天,平年365天),剩余天数为当年的第几天,同时得到目标年份
- 准备平年/闰年的月份天数数组,逐月减去对应月份的天数,剩余天数加1即为日期,同时得到目标月份
参考代码:
// 闰年判断规则:能被4整除但不能被100整除,或能被400整除的年份为闰年 static int is_leap_year(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } void epoch_to_datetime_manual(long epochTime, datetime_t *dt) { // 时分秒计算 dt->sec = epochTime % 60; dt->min = (epochTime % 3600) / 60; dt->hour = (epochTime % 86400) / 3600; long total_days = epochTime / 86400; // 计算星期 dt->dotw = (total_days + 4) % 7; // 计算年份 int year = 1970; while (1) { int year_days = is_leap_year(year) ? 366 : 365; if (total_days < year_days) break; total_days -= year_days; year++; } dt->year = year; // 计算月份和日期 int month_days[] = {31,28,31,30,31,30,31,31,30,31,30,31}; if (is_leap_year(year)) month_days[1] = 29; int month = 0; while (total_days >= month_days[month]) { total_days -= month_days[month]; month++; } dt->month = month + 1; dt->day = total_days + 1; }
内容的提问来源于stack exchange,提问作者DrakeJest
相关产品推荐
相关产品推荐

