如何在C中分解unix时间

mik*_*vis 3 c linux time.h unix-timestamp

这看起来似乎任何人都不应该要做的,但我正在一个内核模块上的嵌入式系统(的OpenWRT),其中似乎time.h 包括timespectime_t类型,以及clock_gettimegmtime功能,但包括localtime,ctime,time或者,或者,批判性地,tm类型.

当我尝试将返回指针从gmtime强制转换为我自己的struct时,我得到了一个段错误.

所以我想我会满足于从两种方式解决这个问题 - 想弄清楚如何访问这个缺失的类型,或者如何推出我自己的方法来分解unix时间戳.

caf*_*caf 5

这应该是准确的(填写一个减少模仿的a struct tm,我year使用Common Era而不是1900 CE时代):

struct xtm
{
    unsigned int year, mon, day, hour, min, sec;
};

#define YEAR_TO_DAYS(y) ((y)*365 + (y)/4 - (y)/100 + (y)/400)

void untime(unsigned long unixtime, struct xtm *tm)
{
    /* First take out the hour/minutes/seconds - this part is easy. */

    tm->sec = unixtime % 60;
    unixtime /= 60;

    tm->min = unixtime % 60;
    unixtime /= 60;

    tm->hour = unixtime % 24;
    unixtime /= 24;

    /* unixtime is now days since 01/01/1970 UTC
     * Rebaseline to the Common Era */

    unixtime += 719499;

    /* Roll forward looking for the year.  This could be done more efficiently
     * but this will do.  We have to start at 1969 because the year we calculate here
     * runs from March - so January and February 1970 will come out as 1969 here.
     */
    for (tm->year = 1969; unixtime > YEAR_TO_DAYS(tm->year + 1) + 30; tm->year++)
        ;

    /* OK we have our "year", so subtract off the days accounted for by full years. */
    unixtime -= YEAR_TO_DAYS(tm->year);

    /* unixtime is now number of days we are into the year (remembering that March 1
     * is the first day of the "year" still). */

    /* Roll forward looking for the month.  1 = March through to 12 = February. */
    for (tm->mon = 1; tm->mon < 12 && unixtime > 367*(tm->mon+1)/12; tm->mon++)
        ;

    /* Subtract off the days accounted for by full months */
    unixtime -= 367*tm->mon/12;

    /* unixtime is now number of days we are into the month */

    /* Adjust the month/year so that 1 = January, and years start where we
     * usually expect them to. */
    tm->mon += 2;
    if (tm->mon > 12)
    {
        tm->mon -= 12;
        tm->year++;
    }

    tm->day = unixtime;
}
Run Code Online (Sandbox Code Playgroud)

我为所有神奇的数字道歉.367*月/ 12是生成日历的30/31天序列的巧妙技巧.计算结果从3月开始直到最后的修正,这使事情变得容易,因为闰日在"年"结束时.