C++计算两个日期年月日的天数差值
时间: 2023-07-11 08:18:55 浏览: 86
可以使用以下代码计算两个日期之间的天数差值:
```c++
#include <iostream>
using namespace std;
int daysInMonth(int year, int month) {
switch (month) {
case 2:
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
return 29;
} else {
return 28;
}
case 4:
case 6:
case 9:
case 11:
return 30;
default:
return 31;
}
}
int daysBetweenDates(int year1, int month1, int day1, int year2, int month2, int day2) {
int days = 0;
if (year1 < year2 || (year1 == year2 && month1 < month2) || (year1 == year2 && month1 == month2 && day1 < day2)) {
// Swap the dates so that (year1,month1,day1) is before (year2,month2,day2)
swap(year1, year2);
swap(month1, month2);
swap(day1, day2);
}
while (year1 > year2 || (year1 == year2 && month1 > month2) || (year1 == year2 && month1 == month2 && day1 > day2)) {
days += daysInMonth(year1, month1) - day1 + 1;
day1 = 1;
if (month1 == 12) {
month1 = 1;
year1--;
} else {
month1++;
}
}
days += day2 - day1;
return days;
}
int main() {
int year1, month1, day1, year2, month2, day2;
cout << "Enter the first date (yyyy mm dd): ";
cin >> year1 >> month1 >> day1;
cout << "Enter the second date (yyyy mm dd): ";
cin >> year2 >> month2 >> day2;
int days = daysBetweenDates(year1, month1, day1, year2, month2, day2);
cout << "The number of days between the two dates is: " << days << endl;
return 0;
}
```
这段代码会提示用户输入两个日期,然后调用 `daysBetweenDates` 函数计算它们之间的天数差值,并输出结果。`daysBetweenDates` 函数使用了一个 `daysInMonth` 函数来计算每个月的天数,然后使用一个循环来逐个月地累加天数直到达到第二个日期。
阅读全文