Skip to content

Instantly share code, notes, and snippets.

@notjosh
Created October 26, 2009 04:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notjosh/218418 to your computer and use it in GitHub Desktop.
Save notjosh/218418 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <ctime>
using namespace std;
// here's the class. a constructor, the subtraction operator and the date property
class qDate
{
public:
explicit qDate(time_t aDate);
long operator-(qDate& other);
time_t date;
};
// implement the constructor
qDate::qDate(time_t aDate)
{
date = aDate;
}
// overload subtraction. it's pretty verbose, you could tighten it up, but hopefully obvious enough what's going on.
long qDate::operator-(qDate& other)
{
time_t thisDate = this->date;
time_t otherDate = other.date;
long diffInSeconds;
if (thisDate > otherDate)
{
diffInSeconds = thisDate - otherDate;
}
else
{
diffInSeconds = otherDate - thisDate;
}
long diffInDays = diffInSeconds / 3600 / 24;
return diffInDays;
}
// let's goooo!
int main()
{
// you're going to want to get the date from the user instead of defining it here:
struct tm a = {0, 0, -1, 25, 9, 109}; /* October 25, 2009 */
struct tm b = {0, 0, -1, 14, 5, 109}; /* June 14, 2009 */
time_t x = mktime(&a);
time_t y = mktime(&b);
if ((time_t)(-1) != x && // if we have valid dates
(time_t)(-1) != y)
{
// create the dates qbot style!
qDate qDateX(x);
qDate qDateY(y);
// output the dates, for shits and/or giggles
cout << ctime(&qDateX.date);
cout << ctime(&qDateY.date);
// calculate the difference in days
long difference = qDateX - qDateY;
// inform the user
cout << "difference = " << difference << " days" << endl;
}
else
{
cout << "invalid time format etc" << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment