Created
October 26, 2009 04:16
-
-
Save notjosh/218418 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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