两个日期之间的总天数C ++

时间:2016-11-12 00:38:22

标签: c++

我正在尝试解决一个问题,要求我给出两个日期之间的总天数。我必须处理这两个日期之间的一些问题,例如闰年和用户输入年份的方式。 (例如,如果你输入1和17,代码仍然会给你差异16年(2017年 - 2001年= 16)。我不应该在main()函数中改变任何东西。这是我的代码。< / p>

 #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;
    }

我的上述代码存在问题,请接受我的帮助。当我运行它时,它表示“date”和“date”之间的无效二进制操作。现在,我假设当我初始化int duration = end - start时,我应该有一个数字。我想我在这里做错了是我无法将(end-start)日期类型转换为整数。我以为我的函数getDifference已经解决了这个问题。不知何故,似乎我没有处理这个问题。

1 个答案:

答案 0 :(得分:1)

接受了挑战。

使用此free, open-source, header-only date library

#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()...