系统的localtime不是线程安全的,由于项目的需要,只好自己写了一个,我也测试了一些,没有遇到问题,大家可以使用,希望多提意见。
void localtime_h(time_t time, struct tm* ret_time)
{
static const char month_days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static const bool leap_year[4] = {false, false, true, false};
unsigned int leave_for_fouryear = 0;
unsigned short four_year_count = 0;
unsigned int temp_value = 0;
ret_time->tm_sec = time % 60;
temp_value = time / 60;// 分钟
ret_time->tm_min = temp_value % 60;
temp_value /= 60; // 小时
temp_value += 8;// 加上时区
ret_time->tm_hour = temp_value % 24;
temp_value /= 24; // 天
ret_time->tm_wday = (temp_value + 4) % 7;// 1970-1-1是4
four_year_count = temp_value / (365 * 4 + 1);
leave_for_fouryear = temp_value % (365 * 4 + 1);
int leave_for_year_days = leave_for_fouryear;
int day_count = 0;
int i = 0;
for (i = 0; i < 4; i++)
{
day_count = leap_year[i] ? 366 : 365;
if (leave_for_year_days <= day_count)
{
break;
}
else
{
leave_for_year_days -= day_count;
}
}
ret_time->tm_year = four_year_count * 4 + i + 70;
ret_time->tm_yday = leave_for_year_days;// 这里不是天数,而是标记,从0开始
int leave_for_month_days = leave_for_year_days;
int j = 0;
for (j = 0; j < 12; j++)
{
if (leap_year[i] && j == 1)
{
if (leave_for_month_days <= 29)
{
break;
}
else if (leave_for_month_days == 29)
{
i++;
leave_for_month_days = 0;
break;
}
else
{
leave_for_month_days -= 29;
}
continue;
}
if (leave_for_month_days < month_days[j])
{
break;
}
else if(leave_for_month_days == month_days[j]){
i++;
leave_for_month_days = 0;
break;
}
else
{
leave_for_month_days -= month_days[j];
}
}
ret_time->tm_mday = leave_for_month_days + 1;
ret_time->tm_mon = j;
}