我有这种格式的日期,例如:
12.2.2015
我必须在那个日期添加几天。例如,我必须添加到该日期+ 1000天,所以输出不会是12 . 2 . 2015
但14 . 3 . 2018 ( it's not accurate i did not calculate it).
是否有任何有效的算法来解决这个问题,或者我必须循环它并制定很多条件闰年等?
答案 0 :(得分:0)
所以,让我们说你有
int year = 2015;
int month = 2;
int day = 12;
int offset = 1000;
您可以使用<ctime>
functions,例如mktime
和localtime
,并相信每天有86400秒可以完成您的需要。这样的事情。
#include <ctime>
struct tm orig_date;
orig_date->tm_sec = 0;
orig_date->tm_min = 0;
orig_date->tm_hour = 12; /* midday, so we make space for non-86400 errors */
orig_date->tm_mday = day;
orig_date->tm_mon = month - 1; /* uses 0-11 range */
orig_date->tm_year = year;
orig_date->tm_isdst = 0;
time_t utc = mktime(&orig_date);
utc += (offset * 86400);
struct tm *new_date;
new_date = localtime(&utc);
printf("Old date: %d. %d. %d\n", orig_date.tm_mday, orig_date.tm_mon, orig_date.tm_year);
printf("New date: %d. %d. %d\n", new_date->tm_mday, new_date->tm_mon, new_date->tm_year);
代码将生成以下(我检查的是正确的):
Old date: 12. 1. 2015
New date: 8. 10. 2017