Hi all, bit of a c++ newbie and hoping you might be able to help me with a problem.

I'm trying to calculate the elapsed time between two dates using difftime, however I keep getting an elapsed time of 0. Can anyone see where I'm going wrong? Any help greatfully recieved!

Cheers.

#include <iostream>
#include <time.h>

using namespace std;

int main ()
{

    time_t rawtime,rawtime2;
    struct tm * timeinfo;
    struct tm * timeinfo2;
    int year=2010, month=9 ,day=23;
    double dif;

    time ( &rawtime );

    timeinfo = localtime ( &rawtime );
    timeinfo->tm_year = year - 1900;
    timeinfo->tm_mon = month - 1;
    timeinfo->tm_mday = day;
    timeinfo->tm_min =30;

    mktime ( timeinfo );

    cout << "First date " << asctime (timeinfo) << endl;

    time ( &rawtime2 );
    timeinfo2 = localtime ( &rawtime2 );

    mktime( timeinfo2 );

    cout << "Second date " << asctime (timeinfo2) << endl;

    dif = difftime(rawtime2,rawtime);

    cout << "The time difference between the two dates is " << dif << endl;

}

>mktime ( timeinfo );
I suspect you want this:

rawtime = mktime(timeinfo);

Likewise with rawtime2. Otherwise both will be close enough to the same time (the running time of the program) to compare as 0 seconds.

That's perfect Narue, thanks a lot! The example that I had modified that code from only had the one 'time' to deal with, so not assigning rawtime wasn't a problem. Thanks again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.