需要考虑小时进位


#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>

#define ERROR -1 
#define MyOK 1

//只考虑正偏移
void utc2localtime(time_t tUtcTime,struct tm *ptNow,int iZoneOffset)
{
        int tmp_day = 0;
        int tmp_month = 0; 
	int tmp_year = 0;

	int month[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
	
	if(tUtcTime <= 0 || ptNow == NULL)
	{
		return;
	}
	
	//struct tm *gmtime_r(const time_t *timep, struct tm *result);
	 (void *)gmtime_r(&tUtcTime,ptNow);
	
	 ptNow->tm_year += 1900;

	 ptNow->tm_mon += 1;

	 if(ptNow->tm_mon == 2) // 2 月
	 {
	     if( (ptNow->tm_year % 400 == 0) 
		 	|| (ptNow->tm_year %4 == 0 && ptNow->tm_year % 100 != 0))
	     {
		     month[2] += 1; 
	     }
	 }

    //+ timezone

	 ptNow->tm_hour += iZoneOffset ;
	 
	 if(ptNow->tm_hour >= 24)
	 {
	     tmp_day = 1; 
	     ptNow->tm_hour %= 24;
	 }
         
	 ptNow->tm_mday += tmp_day;

	 if(ptNow->tm_mday > month[ptNow->tm_mon])
	 {
	      ptNow->tm_mday = 1;
          ptNow->tm_mon += 1;
	 }
         

	 if(ptNow->tm_mon > 12)
	 {
         tmp_year = 1;
		 ptNow->tm_mon = 1;
	 }
	
	 ptNow->tm_year += tmp_year;

     return;
	
}
int main()
{

	time_t  time_cur = 0;
	struct tm tmNow;
	int iTimeZoneOffset = 8; //Beijing +8
	
	memset(&tmNow, 0, sizeof(struct tm));
	
	time_cur = time(NULL);

	
	utc2localtime(time_cur,&tmNow,iTimeZoneOffset);
	
	printf("\n %d-%d-%d " , tmNow.tm_year , tmNow.tm_mon , tmNow.tm_mday);
	
	printf(" %d:%d:%d \n" , tmNow.tm_hour, tmNow.tm_min , tmNow.tm_sec); 
	
    return MyOK;
}






Logo

更多推荐