-3

I'm a beginner at c++ and I was struggling with using date. I thought the ctime library might be helpful but I'm not sure.

For my program, I need to let someone enter the date they joined a club, then I need to compare that with the current date to work out a membership fee.

I also wasn't sure of the best way to take in the date (e.g. enter day/month/year separately or together as a string?).

I couldn't find a simple way of doing this and I would greatly appreciate some help. Thank you.

stylersolve
  • 29
  • 1
  • 5

3 Answers3

3

You can get the date from the user and parse it into a tm structure using strptime.

For example:

tm timeDate;
strptime(input_str.c_str(),"%Y-%m-%d %H:%M", &timeDate); // define date / time format convenient for you here; this is just an example

Then convert to a time_t type:

time_t time_input = mktime(&timeDate);

Then compare with another time_t (created the same way or by getting the current system time or whatever you need);

double timeDiff = difftime(time_input, other_time_t_value);

Resources used:

time tutorial

similar question

related question

Another option might be the Boost datetime library (I don't remember using it myself so I won't do more than refer you) recommended here

A note to others reading this question: the OP I believe is not using C++11 or later. If you are, this answer might be better for you.

Basya
  • 1,477
  • 1
  • 12
  • 22
1

Reference https://stackoverflow.com/a/997988/3989888

#include <ctime>
#include <iostream>
using namespace std;

int main() {
    time_t t = time(0);   // get time now
    struct tm * now = localtime( & t );
    cout << (now->tm_year + 1900) << ' ' 
         << (now->tm_mon + 1) << ' '
         <<  now->tm_mday
         << endl;

    cout<<"Enter Date YYYY MM DD"<<endl;
    int y,m,d;
    cin>>y;
    cin>>m;
    cin>>d;

    cout<<"Member since: "<<y-now->tm_year-1900<<" years "<<m-now->tm_mon-1<<" months "<<d-now->tm_mday<<" days "<<endl;

}
rainversion_3
  • 887
  • 1
  • 14
  • 30
  • Thank you! This is extremely helpful but is there a way to combat the negative months/days? Maybe I could use an if statement and sort through them (although I wouldn't know what to do with months of varying lengths). – stylersolve Sep 12 '17 at 17:27
0

Seriously now? Please write modern code and use. std::chrono::duration.

Something like

#include <chrono>
#include <iostream>

int main() {
  auto long_ago =
    std::chrono::system_clock::time_point();
  std::chrono::duration<double> diff =
    std::chrono::system_clock::now() - long_ago;
  std::cout << "Seconds since Jan 1 1970: " << diff.count() << std::endl;
}
Kaveh Vahedipour
  • 3,412
  • 1
  • 14
  • 22
  • 1
    #1: Please be respectful of others. #2: the OP commented that he is not using a compiler which supports this. – Basya Sep 12 '17 at 18:25