Search code examples
c++timectimetime-tdifftime

difference of two user entered time c++


i need to be able fill two variables (a kind of time variable), then be able to calculate their difference. after all of my searches i found difftime, but my problem is that, it uses time_t variables, and i don't know how to fill a 'time_t' with time which i want. for example i want to user enter time_1 and time_2 as (10:04, 11:05) and it be able to show difference in sec or minute or hour or anything.(for example 61 min)

i tried as blow but it didn't worked:

#include <iostream>
#include <ctime>
using namespace std;
void main()
{
    tm time_1 = {0, 0, 0, 1, 0, 0, 0, 0, 0};
    tm time_2 = {0, 0, 0, 1, 0, 0, 0, 0, 0};

    time_1.tm_hour = 10;
    time_1.tm_min = 4;

    time_2.tm_hour = 11;
    time_2.tm_min = 5;

    double diff = difftime (mktime(&time_2),mktime(&time_1));

    cout << diff << endl;

    system("pause");
}

Solution

  • std::tm has the following members (http://en.cppreference.com/w/cpp/chrono/c/tm):

    int tm_sec;  // seconds after the minute – [0, 61](until C++11) / [0, 60] (since C++11)
    int tm_min;  // minutes after the hour – [0, 59]
    int tm_hour; // hours since midnight – [0, 23]
    int tm_mday; // day of the month – [1, 31]
    int tm_mon;  // months since January – [0, 11]
    int tm_year; // years since 1900
    int tm_wday; // days since Sunday – [0, 6]
    int tm_yday; // days since January 1 – [0, 365]
    int tm_isds; // Daylight Saving Time flag.
    

    You have initialized only couple of those members. The rest are uninitialized for both the objects.

    Hence, your program has undefined behavior.

    To see a predictable behavior, initialize the objects properly. One way is to use:

     tm time_1 = {0, 0, 0, 1, 0, 0, 0, 0, 0};
     tm time_2 = {0, 0, 0, 1, 0, 0, 0, 0, 0};
    

    before reading user input.

    Update

    Using

    std::time_t t = std::time(NULL);
    std::tm time_1 = *std::localtime(&t);
    tm time_2 = time_1;
    

    To initialize time_1 and time_2 seems to work for me.

    See it working at http://ideone.com/AmCzTu.