Guest User

Untitled

a guest
Apr 23rd, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. #include <iostream>
  2. #include <ctime>
  3.  
  4. using namespace std;
  5.  
  6. // here's the class. a constructor, the subtraction operator and the date property
  7. class qDate
  8. {
  9. public:
  10. explicit qDate(time_t aDate);
  11. long operator-(qDate& other);
  12. time_t date;
  13. };
  14.  
  15. // implement the constructor
  16. qDate::qDate(time_t aDate)
  17. {
  18. date = aDate;
  19. }
  20.  
  21. // overload subtraction. it's pretty verbose, you could tighten it up, but hopefully obvious enough what's going on.
  22. long qDate::operator-(qDate& other)
  23. {
  24. time_t thisDate = this->date;
  25. time_t otherDate = other.date;
  26.  
  27. long diffInSeconds;
  28.  
  29. if (thisDate > otherDate)
  30. {
  31. diffInSeconds = thisDate - otherDate;
  32. }
  33. else
  34. {
  35. diffInSeconds = otherDate - thisDate;
  36. }
  37.  
  38. long diffInDays = diffInSeconds / 3600 / 24;
  39. return diffInDays;
  40. }
  41.  
  42. // let's goooo!
  43. int main()
  44. {
  45. // you're going to want to get the date from the user instead of defining it here:
  46. struct tm a = {0, 0, -1, 25, 9, 109}; /* October 25, 2009 */
  47. struct tm b = {0, 0, -1, 14, 5, 109}; /* June 14, 2009 */
  48. time_t x = mktime(&a);
  49. time_t y = mktime(&b);
  50.  
  51. if ((time_t)(-1) != x && // if we have valid dates
  52. (time_t)(-1) != y)
  53. {
  54. // create the dates qbot style!
  55. qDate qDateX(x);
  56. qDate qDateY(y);
  57.  
  58. // output the dates, for shits and/or giggles
  59. cout << ctime(&qDateX.date);
  60. cout << ctime(&qDateY.date);
  61.  
  62. // calculate the difference in days
  63. long difference = qDateX - qDateY;
  64.  
  65. // inform the user
  66. cout << "difference = " << difference << " days" << endl;
  67. }
  68. else
  69. {
  70. cout << "invalid time format etc" << endl;
  71. }
  72.  
  73. return 0;
  74. }
Add Comment
Please, Sign In to add comment