mxbinfen

自己写了一个线程安全的localtime

系统的localtime不是线程安全的,由于项目的需要,只好自己写了一个,我也测试了一些,没有遇到问题,大家可以使用,希望多提意见。

void localtime_h(time_t time, struct tm* ret_time)
{
    
static const char month_days[12= {312831303130313130313031};
    
static const bool leap_year[4= {falsefalsetruefalse};

    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;
}

posted on 2009-07-23 17:28 超越时空思念 阅读(1583) 评论(2)  编辑 收藏 引用

Feedback

# re: 自己写了一个线程安全的localtime 2010-09-04 22:56 主打歌

正好2000年是闰年,不然你惨了。不过正好100年内不错,不管了。
还有那个夏时令的标志最好清空设置
ret_time->tm_isdst = 0;
多谢先生了。  回复  更多评论   

# re: 自己写了一个线程安全的localtime 2012-05-16 20:29 aaaaa

测试了下,运行结果是正确的!
谢谢了。
拿来学习下!  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理