伸手党留个评论就可以拷走使用!!!
DEV C++编译可用,输出正确
可优化处欢迎讨论!
#include"stdio.h"
#include "stdint.h"
#include <string.h>
#define TIME_ZONE 8 //北京时间
uint8_t Common_month_day[12]={
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; //平年
uint8_t Leap_month_day[12] ={
31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; //闰年
typedef struct
{
uint32_t Year; // 1970~2038
uint8_t Month; // 1~12
uint8_t Day; // 1~31
uint8_t Hour; // 0~23
uint8_t Min; // 0~59
uint8_t Sec; // 0~59
}UTC_TIME_T;
UTC_TIME_T Standard_Time = {
0};
unsigned int year_days(unsigned int year)
{
return ( ((year%4 == 0 && year%100 != 0) || (year%400 == 0)) ? 366 : 365 );
}
void* unix_to_time(unsigned long long unix)
{
UTC_TIME_T* time_p = &Standard_Time;
uint32_t day_total = 0;
uint32_t day_compare = 0;
uint32_t sec_total = 0;
if(unix > 2147483647) //32 位限制,0x7FFFFFFF
unix = 0;
unix += (TIME_ZONE*60*60); //时区的差值
day_total = unix/(60*60*24);
sec_total = unix%(60*60*24);
for( time_p->Year = 1970; time_p->Year < 2039; time_p->Year ++ )
{
day_compare += year_days(time_p->Year);
if( day_total < day_compare)
{
day_total -= (time_p->Year == 1970) ? 0 : (day_compare - year_days(time_p->Year));
break;
}
}
for( day_compare = 0,time_p->Month = 1; time_p->Month < 13; time_p->Month ++ )
{
day_compare += ( year_days( time_p->Year ) == 366 ) ? Leap_month_day[time_p->Month-1] : Common_month_day[time_p->Month-1] ;
if( day_total < day_compare)
{
if(time_p->Month != 1)
day_total -= ( year_days( time_p->Year ) == 366 ) ? (day_compare - Leap_month_day[time_p->Month-1]) : (day_compare - Common_month_day[time_p->Month-1]);
time_p->Day = ++day_total;
break;
}
}
time_p->Hour = sec_total/(60*60);
time_p->Min = (sec_total%(60*60))/60;
time_p->Sec = sec_total%60;
return time_p;
}
unsigned long long time_to_unix(void* time_input)
{
unsigned int temp = 0;
unsigned long long unix = 0;
UTC_TIME_T *time = (UTC_TIME_T*) time_input;
for( temp = 1970; temp < time->Year; temp++ )
unix += year_days( temp )*(60*60*24);
for( temp = 1; temp < time->Month; temp++ )
unix += (60*60*24)*((year_days(time->Year) == 366) ? (Leap_month_day[temp-1]) : (Common_month_day[temp-1])) ;
unix += (time->Day - 1) * (60*60*24);
unix += time->Hour * (60*60);
unix += time->Min * 60;
unix += time->Sec;
unix -= (TIME_ZONE*60*60); //减时区
return unix;
}
int main()
{
unsigned long long temp;
unsigned long long unix_long;
UTC_TIME_T *time_temp;
while(1)
{
printf("input unix:");
scanf("%lld",&temp);
time_temp = unix_to_time( temp );
unix_long = time_to_unix( time_temp );
printf("%4d-%02d-%02d %02d:%02d:%02d unix:%lld\r\n",time_temp->Year,time_temp->Month,time_temp->Day,time_temp->Hour,time_temp->Min,time_temp->Sec,unix_long);
}
return 0;
}
#if 0
unsigned long long byte_to_long(uint8_t high_three, uint8_t high_two, uint8_t low_one,uint8_t low_zero)
{
return (high_three*16777216 + high_two*65536 + low_one*256 + low_zero);
}
#endif