Unix时间戳转换成日期

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值