Unix时间戳(秒)是32位有符号整型数(int),时间的起点是1970年1月1月1日0:0:0,也称为epoch time。在线转换见Epoch Converter - Unix Timestamp Converter
C语言实现时间戳与日期转换:
/* Leap year between 1970 and 2038: 1972、1976、1980、1984、1988、
1992、1996、2000、2004、2008、2012、2016、2020、2024、2028、2032、2036 */
/* 1 hour = 3600 sec, 1 day = 86400 sec, 365 days = 31, 536, 000 sec */
typedef struct
{
int year;
char month;
char day;
char hour;
char minute;
char second;
} tm;
int stamptodate(int *Tstamp, tm *T_outp)
{
if (*Tstamp < 0)
{
return -1; // input should not be negtive numbers
}
char Is_leap = 0; // Leap year flag
int Day_of_Month[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int Year_Past = (*Tstamp) / 31536000; // get year from 1970, year = 365day
int Sec_of_Cur_Year = (*Tstamp) % 31536000; // seconds since this year
int LeapYear_Past = 0; // count of leap year since 1970
if (Year_Past > 2) // since 1972, i.e. Year_Past = 2
{
LeapYear_Past = (Year_Past - 2) / 4 + 1; // every four year is leap year
}
Sec_of_Cur_Year -= LeapYear_Past * 86400; // leap year has 1 more day
if (Sec_of_Cur_Year < 0)
{
Sec_of_Cur_Year += 31536000;
Year_Past--;
if ((Year_Past - 2) % 4 == 0) // Current year is leap year
{
Sec_of_Cur_Year += 86400; // Leap year 2/29 has been subtracted before, add back here
Is_leap = 1;
}
}
else
{
if ((Year_Past - 2) % 4 == 0)
{
Is_leap = 1;
}
}
T_outp->year = 1970 + Year_Past;
int Day_of_Cur_Year = Sec_of_Cur_Year / 86400;
if (Is_leap)
{
Day_of_Month[1]++; // Feb of leap year has 29 days
}
for (int i = 0; i < 12; i++)
{
if (Day_of_Cur_Year < Day_of_Month[i])
{
T_outp->month = i + 1;
T_outp->day = Day_of_Cur_Year + 1;
break;
}
else
{
Day_of_Cur_Year -= Day_of_Month[i];
}
}
/*-------time process: hour:minute:second -------------*/
int Sec_of_Cur_Day = (*Tstamp) % 86400;
T_outp->hour = Sec_of_Cur_Day / 3600;
T_outp->minute = (Sec_of_Cur_Day / 60) % 60;
T_outp->second = Sec_of_Cur_Day % 60;
return 0;
}