我有一个结构TM.
我需要在tm结构中添加一些固定的间隔(在xx年,xx个月,xx天给出).
这有什么标准功能吗?
我使用的编译器是Windows XP上的MSVC 2005.
Vov*_*ium 11
转换时间格式有两个功能:
mktime()它将struct tm(代表当地时间)转换为time_t.localtime()转换time_t为当地时间struct tm.Interesing是第一个,它接受超出范围的struct成员值,并作为转换的副产品,适当地设置它们(和所有其他).这可以用于在算术运算之后校正字段数据值.但是,字段类型为int,因此可能存在溢出(在16位系统上),例如,如果您在一年中添加秒数.
因此,如果您想要实际日期,此代码将有所帮助(来自@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;
}
Run Code Online (Sandbox Code Playgroud)
还要注意tm_isdst会员,关心它.当你跳过白天时间切换日期时,它的值可能会导致时间前后移动.
标准加法运算符有效.
struct tm x;
/* add 2 years and 3 days to x */
x.tm_year += 2;
x.tm_mday += 3;
Run Code Online (Sandbox Code Playgroud)
编辑:您可以轻松地创建一个功能
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;
}
Run Code Online (Sandbox Code Playgroud)
编辑:添加mktime到标准化结果