- c语言中对日期做加减操作非常不方便,不想c++有现成的类可以使用。
- 以下是通过c的方式写的一个计算函数,可以加减日期。
- (没有经过严格测试,如有问题,请指出,谢谢。)
- /**
-
*时间计算 例如 ( 2011-10-12 11:00:00 ) +( 00-14-10 03:00:00 ) = (2012-12-22 14:00:38)
-
@param old_time 参与运算的时间
-
@param offset 需要加减的偏移值
-
@param is_add 操作 (0:对时间做减法操作,1:做加法操作)
-
@return 返回计算的结果时间
-
*/
-
struct tm clac_time( struct tm old_time, struct tm offset, int is_add )
-
{
-
int year_day[2][12] = {{31,28,31,30,31,30,31,31,30,31,30,31},
-
{31,29,31,30,31,30,31,31,30,31,30,31}};
-
time_t old_sec = mktime( &old_time ); //距离1900-1-1的秒数
-
-
/*加上1900,计算的闰年才是准确的*/
-
old_time.tm_year += 1900;
-
old_time.tm_mon += 1;
-
-
int is_leap_year = 0, day_count = 0;
-
size_t time_second_counts = 0; /*偏差的秒数*/
-
/*先计算年月,得出相差的天数*/
-
int offset_mon = offset.tm_year * 12 + offset.tm_mon;
-
int year = old_time.tm_year;
-
int mon = old_time.tm_mon;
-
while ( offset_mon > 0 )
-
{
-
if ( is_add > 0 )
-
{
-
mon++;
-
if ( mon > 12 )
-
{
-
mon = 1;
-
year++;
-
}
-
-
if ( (year%400==0) || ( (year%100!=0) && (year%4==0) ) )
-
is_leap_year = 1;
-
else
-
is_leap_year = 0;
-
-
/*加的是上个月的天数*/
-
int index = ( mon == 1 ) ? 11:(mon-2);
-
day_count += year_day[is_leap_year][index];
-
}
-
else
-
{
-
mon--;
-
if ( mon < 1)
-
{
-
mon = 12;
-
year--;
-
}
-
-
if ( (year%400==0) || ( (year%100!=0) && (year%4==0) ) )
-
is_leap_year = 1;
-
else
-
is_leap_year = 0;
-
-
/*减的是上个月的天数*/
-
int index = ( mon == 1 ) ? 11:(mon-2);
-
day_count += year_day[is_leap_year][index];
-
}
-
-
offset_mon--;
-
}
-
time_second_counts += (day_count * 24 * 60 * 60);
-
-
/*然后加上剩下的 日时分秒 */
-
time_second_counts += ( offset.tm_mday* 24 * 60 * 60 +
-
offset.tm_hour * 60 * 60 +
-
offset.tm_min * 60 + offset.tm_sec );
-
-
if ( is_add > 0 )
-
old_sec += time_second_counts ;
-
else
-
old_sec -= time_second_counts ;
-
-
struct tm result;
-
localtime_r(&old_sec, &result);
-
-
return result;
- }