添加一些间隔到tm结构
我有一个结构。
我需要在tm结构中添加一些固定的间隔(在xx年,xx个月,xx天给出)。
这有什么标准function吗?
我使用的编译器是Windows XP上的MSVC 2005。
转换时间格式有两个function:
-
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; }
还要注意关于tm_isdst
成员,关心它。 当你跳过白天时间切换日期时,它的值可能会导致时间前后移动。
标准加法运算符有效。
struct tm x; /* add 2 years and 3 days to x */ x.tm_year += 2; x.tm_mday += 3;
编辑:您可以轻松地创建一个function
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
以规范化结果
我建议先将手头的日期转换为天数。 然后添加间隔是微不足道的。 然后,将数字转换回日期。
您可以找到算法,以便将日期保存到天数,然后返回到http://alcor.concordia.ca/~gpkatch/gdate-algorithm.html
其他答案会导致高度不稳定的结果,具体取决于系统初始化struct tm以及中午时间值是否已正确初始化。
如果你感兴趣的只是日期的变化,而时间保持不变,那么在传递给mktime
之前将tm_isdst
, tm_hour
, tm_sec
all设置为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; }
我希望它更简单,但这就是它必须如何。