两个日期之间的总天数

Total days between 2 dates C++

本文关键字:之间 日期 两个      更新时间:2023-10-16

我正试图解决一个问题,要求我给出两个日期之间的总天数。

我必须处理这两个日期之间的一些问题,比如闰年和用户输入年份的方式。(例如,如果你输入1和17,代码仍然会给你16年的差(2017 - 2001 = 16)。我不应该改变main()函数内部的任何东西。

这是我的代码。

 #include <iostream>
 #include <cmath>
 using namespace std;
 class date
 {
    private:
    int m;
    int d;
    int y;
    public:
    date(int, int, int);
    int countLeapYears(date&);
    int getDifference(date&);
    int operator-(date&);    
  };
   int main()
   {
    int day, month, year;
    char c;
    cout << "Enter a start date: " << endl;
    cin >> month >> c >> day >> c >> year;
    date start = date(month, day, year);
    cout << "Enter an end date: " << endl;
    cin >> month >> c >> day >> c >> year;
    date end = date(month, day, year);
    int duration = end-start;
     cout << "The number of days between those two dates are: " <<    
     duration << endl;
     return 0;
   }

    date::date(int a, int b, int c)
    {
    m = a;
    d = b;
    y = c;
    }
    const int monthDays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31,   
    30, 31};
   int date::countLeapYears(date& d)
   {
      int years = d.y;
      if (d.m <= 2)
      years--;
      return years / 4 - years / 100 + years / 400;
    }
   int date::getDifference(date& other)
   {
      int n1 = other.y*365 + other.d;
      for (int i=0; i<other.m - 1; i++)
     {
       n1 += monthDays[i];
       n1 += countLeapYears(other);
      }
      return n1;
      }
   int date::operator-(date& d) {
      int difference = getDifference(d);
      return difference;
    }

当我运行这段代码时,它显示的是invalid binary operation between "date" and "date"

现在,我假设当我初始化int duration = end - start时,我应该得到一个数字。我猜我在这里做错的是我没有把(结束-开始)日期类型转换成一个整数。我认为我的函数getDifference已经解决了这个问题,但显然它没有。

接受挑战

使用这个免费的、开源的、只有头文件的日期库:

#include "date.h"
#include <iostream>
namespace me
{
class date
{
    ::date::sys_days tp_;
public:
    date(int month, int day, int year)
        : tp_{::date::year(year)/month/day}
        {}
    friend
    int
    operator-(const date& x, const date& y)
    {
        return (x.tp_ - y.tp_).count();
    }
};
}  // namespace me
using namespace std;
#define date me::date
int main()...