Joseph
Joseph

Reputation: 85

Total days between 2 dates C++

I am trying to solve a problem that asks me to give the total days between two dates.

I have to take care of some issues between those two dates, such as leap years and the way of inputting the years by the users. (For example, if you input 1 and 17, the code will still give you the difference is 16 years (2017 - 2001 = 16). I am not supposed to change ANYTHING inside the main() function.

Here is my code.

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

When I ran this code, it said invalid binary operation between "date" and "date".

Now, I assume that when I initialized int duration = end - start, I should have gotten a number. I guess what I am doing wrong here is I failed to convert the (end - start) date type into an integer. I thought my function getDifference already took care of that issue, but apparently it did not.

Upvotes: 1

Views: 4212

Answers (1)

Howard Hinnant
Howard Hinnant

Reputation: 218710

Challenge accepted.

Using this 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()...

Upvotes: 3

Related Questions