这似乎喜欢的东西没有人应该要做,但是我工作的一个核心模块,用于嵌入式系统(本项目)在这似乎 time.h 包括 timespectime_t 类型,以及 clock_gettimegmtime 功能,但并 包括 localtime, ctime, time, 或者,极度, tm 类型。

当我试图投返回的指针,从gmtime到我自己的结构,我获得一个出现段错误.

所以我想我能内容,以解决该问题的两个方法—这会是伟大的图找出如何获得失的类型,或者,如何推我自己的方法解unix时间戳。

有帮助吗?

解决方案

此应该是准确的(填写了struct tm的切口向下仿,我的year使用共同的时代,而不是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;
}

我的道歉对于所有的幻数。 367 *月/ 12是一个巧妙的方法来产生日历的30/31天序列。计算可与年中开始在三月直到修正到了最后,这让事情变得容易,因为那时的闰日落在一个“年”的结束。

其他提示

在用户空间glibc就做了很多工作,至于处理时间表示的“本地”的一部分。在内核中,这是不可用。也许你不应该尝试你的模块中与此打扰,如果需要做它在用户空间。

一个 time_t 是的数秒钟,因为一月1日,1970年以分解,成为一个月、天和今年是不是困难的前提是你想要的结果在UTC。还有一个 一群的来源 通过谷歌上搜索 "gmtime源".最嵌入式系统离开了当地时间处理,因为它是一个小小的更多困难,因为所依赖的时区设置和环境。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top