1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| #include <iostream>
using namespace std;
bool isLeap(int year) { return (year % 4 == 0 || year % 400 == 0) && (year % 100 != 0); }
int daysOfYear(int year) { return isLeap(year) ? 366 : 365; }
int dayOfYear(int year, int month, int day) { int DAY[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; if (isLeap(year)) { DAY[1] = 29; } for (int i = 0; i < month - 1; ++i) { day += DAY[i]; } return day; }
bool stringToDate(string date, int& year, int& month, int& day) { year = atoi(date.substr(0, 4).c_str()); month = atoi(date.substr(4, 2).c_str()); day = atoi(date.substr(6, 2).c_str()); int DAY[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; if (isLeap(year)) { DAY[1] = 29; } return year >= 0 && month <= 12 && month > 0 && day <= DAY[month - 1] && day > 0; }
int daysBetween2Date(string date1, string date2) { int year1, month1, day1; int year2, month2, day2; if (!stringToDate(date1, year1, month1, day1) || !stringToDate(date2, year2, month2, day2)) { cout << "输入的日期格式不正确"; return -1; } if (year1 == year2 && month1 == month2) { return day1 > day2 ? day1 - day2 : day2 - day1; } else if (year1 == year2) { int d1, d2; d1 = dayOfYear(year1, month1, day1); d2 = dayOfYear(year2, month2, day2); return d1 > d2 ? d1 - d2 : d2 - d1; } else { if (year1 > year2) { swap(year1, year2); swap(month1, month2); swap(day1, day2); } int d1, d2, d3; if (isLeap(year1)) { d1 = 366 - dayOfYear(year1, month1, day1); } else { d1 = 365 - dayOfYear(year1, month1, day1); } d2 = dayOfYear(year2, month2, day2); d3 = 0; for (int year = year1 + 1; year < year2; year++) { if (isLeap(year)) d3 += 366; else d3 += 365; } return d1 + d2 + d3; } }
int main() {
int days = daysBetween2Date("20101111", "20111111"); cout << "相差 " << days << " 天" << endl;
int days2 = daysBetween2Date("20200202", "20200131"); cout << "相差 " << days2 << " 天" << endl;
int days3 = daysBetween2Date("20230712", "20050619"); cout << "相差 " << days3 << " 天" << endl;
return 0; }
|