如何计算两个日期之间的天数。日期ar保存在整数变量(数组)中。如果有一些功能会很棒。如果不是,我尝试使用for循环,但没找到正确的算法。
#include <iostream>
int stoi(std::string s);
int main(){
/* 5th november of 2013 */
int days1[0] = 05;
int days1[1] = 11;
int days1[2] = 2013;
/* 7th october of 2016 */
int days2[0] = 07;
int days2[1] = 10;
int days2[2] = 2016;
int days = date(days1,days2);
std::cout << days << std::endl;
return 0;
}
int date(int dates1[], int date2[]){
int days = 0;
/* Task: how much days is past */
/* Days in each month must be real (31 or 30 or 29/28) */
/* there can't be constant as 31 days on each month or 365 days in year */
return days;
}
答案 0 :(得分:0)
您可能会发现这个感兴趣的epoch calculator code。 用C语言编写,但很容易转换为C ++。
答案 1 :(得分:0)
#include <iostream>
#include <ctime>
#include <cmath>
auto date(int date1[], int date2[]){
std::tm dur[2] {{0,0,0,date1[0],date1[1]-1,date1[2]-1900},{0,0,0,date2[0],date2[1]-1,date2[2]-1900}};
std::time_t t1 {std::mktime(dur)}, t2 {std::mktime(dur+1)};
if ( t1 != (std::time_t)(-1) && t2 != (std::time_t)(-1) ){
return std::difftime(t2, t1) / (60 * 60 * 24);
}else{
return (double)INFINITY;
//alternative: throw exception
}
}
int main(){
/* 5th november of 2013 */
int days1[] = {5,11,2013};
/* 7th october of 2016 */
int days2[] = {7,10,2016};
auto days = date(days1,days2);
if(std::isinf(days)){
std::cout << "cannot convert to time_t" << std::endl;
}else{
std::cout << days << std::endl;
}
return 0;
}
这应该打印1067。