对tm结构添加一些间隔

时间:2010-11-18 11:52:32

标签: c time-t ctime

我有一个结构 tm 我需要添加一些固定的间隔(在xx年,xx个月,xx天给出) 到 tm 结构。
有没有标准功能呢?

我使用的编译器是Windows XP上的MSVC 2005。

4 个答案:

答案 0 :(得分:10)

有两种功能可以转换时间格式:

  1. mktime()struct tm(代表当地时间)转换为time_t
  2. localtime()time_t转换为struct tm中的当地时间。
  3. Interesing是第一个,它接受超出范围的struct成员值,并作为转换的副产品,适当地设置它们(和所有其他)。这可以用于在算术运算之后校正字段数据值。但是,字段类型为int,因此可能存在溢出(在16位系统上),如果e。 G。你可以在一年内增加秒数。

    因此,如果你想拥有实际日期,这段代码会有所帮助(来自@pmg的修改后的答案副本):

    struct tm addinterval(struct tm x, int y, int m, int d) {
        x.tm_year += y;
        x.tm_mon += m;
        x.tm_mday += d;
        mktime(&x);
        return x;
    }
    

    还要注意tm_isdst成员,关心它。当你跳过白天时间切换日期时,它的值可能会导致时间前后移动。

答案 1 :(得分:9)

标准加法运算符有效。

struct tm x;
/* add 2 years and 3 days to x */
x.tm_year += 2;
x.tm_mday += 3;

编辑:您可以轻松制作一个功能

struct tm addinterval(struct tm x, int y, int m, int d) {
    x.tm_year += y;
    x.tm_mon += m;
    x.tm_mday += d;
    mktime(&x); /* normalize result */
    return x;
}

编辑:添加mktime以规范化结果

答案 2 :(得分:0)

我建议先将手头的日期转换为天数。然后添加间隔是微不足道的。然后,将数字转换回日期。

您可以找到将日期记录到若干天的算法,然后返回到例如http://alcor.concordia.ca/~gpkatch/gdate-algorithm.html

答案 3 :(得分:0)

其他答案会导致高度不稳定的结果,具体取决于系统初始化struct tm以及中午时间值是否已正确初始化。

如果你感兴趣的只是日期的变化,而时间保持不变,那么在传递给tm_isdst之前,将tm_hourtm_secmktime全部设置为0。更好的是,之前获取它们的值并在之后重置它们以保持一致性(如果之前它们不一致,它们将始终如此)。重用其他答案中的代码:

tm addinterval(tm t, int y, int m, int d)
{
    auto hour = t.tm_hour;
    auto min = t.tm_min;
    auto sec = t.tm_sec;

    // First we discover the DST Flag. By setting hour to 12
    //   we can assure the mktime does not shift the date
    //   because it will shift the hour!
    t.tm_isdst = 0;
    t.tm_hour = 12;
    t.tm_min = 0;
    t.tm_sec = 0;
    mktime(&t);

    // Now we can add the interval
    t.tm_year += y;
    t.tm_mon += m;
    t.tm_mday += d;
    mktime(&t);

    // Now reset the mid-day time values
    t.tm_hour = hour;
    t.tm_min = min;
    t.tm_sec = sec;

    // Return struct tm while keeping mid-day time the same
    //   while the only values that changed are the date and perhaps isdst.
    return t;
}

我希望它更简单,但那就是它必须如何。