2016-04-02 216 views
0

我有這種格式,例如日期:日期格式 - 添加天日期

12.2.2015 

我有天添加到該日期。例如我必須添加到該日期+ 1000天,所以輸出不會是12 . 2 . 2015,但14 . 3 . 2018 (it's not accurate i did not calculate it).是否有任何有效的算法解決這個問題,或者我必須循環它,並使閏年等很多條件?

+3

這是一門功課的任務嗎?幾乎相同的問題(即使是相同的標籤)幾乎與您同時問:http://stackoverflow.com/questions/36372774/date-and-time-manipulation – dfri

回答

0

因此,讓我們說你有

int year = 2015; 
int month = 2; 
int day = 12; 
int offset = 1000; 

您可以利用<ctime>functionsmktimelocaltime和信念,每天都有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