【发布时间】:2017-04-29 18:39:43
【问题描述】:
如何计算两个日期之间的天数。日期保存在整数变量(数组)中。如果有一些功能会很棒。如果不是,我尝试了一些 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;
}
【问题讨论】:
-
计算从开始日期(例如 01.01.1970)到当前日期的时间(以秒为单位)。对你的两个日期都这样做。然后减去两者,然后将结果计算回分钟/小时/天或月。
-
你可以使用 std::chrono::duration
-
使用增强。它有一个日期时间处理模块。
-
在链接的副本中,don't miss Howard Hinnant's excellent answer(因为它还没有被投票到顶部)。
标签: c++