UNIX Time 時間戳 與 北京時間 相互轉換

typedef struct t_xtime {
  int year; int month;  int day;   
  int hour; int minute;  int second; 
} _xtime ;

#define xMINUTE   (60             ) //1分的秒數
#define xHOUR      (60*xMINUTE) //1小時的秒數
#define xDAY        (24*xHOUR   ) //1天的秒數
#define xYEAR       (365*xDAY   ) //1年的秒數

 

能夠經過在線轉換工具,對程序結果進行驗證:http://tool.chinaz.com/Tools/unixtime.aspx工具

 

 

將localtime(UTC+8北京時間)轉爲UNIX TIME,以1970年1月1日爲起點 unix

 

unsigned int  xDate2Seconds(_xtime *time)
{
  static unsigned int  month[12]={
    /*01月*/xDAY*(0),
    /*02月*/xDAY*(31),
    /*03月*/xDAY*(31+28),
    /*04月*/xDAY*(31+28+31),
    /*05月*/xDAY*(31+28+31+30),
    /*06月*/xDAY*(31+28+31+30+31),
    /*07月*/xDAY*(31+28+31+30+31+30),
    /*08月*/xDAY*(31+28+31+30+31+30+31),
    /*09月*/xDAY*(31+28+31+30+31+30+31+31),
    /*10月*/xDAY*(31+28+31+30+31+30+31+31+30),
    /*11月*/xDAY*(31+28+31+30+31+30+31+31+30+31),
    /*12月*/xDAY*(31+28+31+30+31+30+31+31+30+31+30)
  };
  unsigned int  seconds = 0;
  unsigned int  year = 0;
  year = time->year-1970;       //不考慮2100年千年蟲問題
  seconds = xYEAR*year + xDAY*((year+1)/4);  //前幾年過去的秒數
  seconds += month[time->month-1];      //加上今年本月過去的秒數
  if( (time->month > 2) && (((year+2)%4)==0) )//2008年爲閏年
    seconds += xDAY;            //閏年加1天秒數
  seconds += xDAY*(time->day-1);         //加上本天過去的秒數
  seconds += xHOUR*time->hour;           //加上本小時過去的秒數
  seconds += xMINUTE*time->minute;       //加上本分鐘過去的秒數
  seconds += time->second;               //加上當前秒數
 seconds -= 8 * xHOUR; return seconds; }

  

將UNIX時間轉爲UTC+8 即北京時間blog

//UNIX轉爲UTC 已進行時區轉換 北京時間UTC+8
void xSeconds2Date(unsigned long seconds,_xtime *time )
{
	static unsigned int month[12]={
		/*01月*/31,  
		/*02月*/28,  
		/*03月*/31,  
		/*04月*/30,  
		/*05月*/31,  
		/*06月*/30,  
		/*07月*/31,  
		/*08月*/31,  
		/*09月*/30,  
		/*10月*/31,  
		/*11月*/30,  
		/*12月*/31  
	};
	unsigned int days;  
	unsigned short leap_y_count;  
	time->second      = seconds % 60;//得到秒  
	seconds          /= 60;  
	time->minute      =  seconds % 60;//得到分  
	seconds			 += 8 * 60 ;		//時區矯正 轉爲UTC+8 bylzs
	seconds          /= 60;  
	time->hour        = seconds % 24;//得到時  
	days              = seconds / 24;//得到總天數  
	leap_y_count = (days + 365) / 1461;//過去了多少個閏年(4年一閏)  
	if( ((days + 366) % 1461) == 0)  
	{//閏年的最後1天  
		time->year = 1970 + (days / 366);//得到年  
		time->month = 12;              //調整月  
		time->day = 31;  
		return;  
	}  
	days -= leap_y_count;  
	time->year = 1970 + (days / 365);     //得到年  
	days %= 365;                       //今年的第幾天  
	days = 01 + days;                  //1日開始  
	if( (time->year % 4) == 0 )  
	{  
		if(days > 60)--days;            //閏年調整  
		else  
		{  
			if(days == 60)  
			{  
				time->month = 2;  
				time->day = 29;  
				return;  
			}  
		}  
	}  
	for(time->month = 0;month[time->month] < days;time->month++)  
	{  
		days -= month[time->month];  
	}  
	++time->month;               //調整月  
	time->day = days;           //得到日  
}
相關文章
相關標籤/搜索