1

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");
}

1 Answers1

2

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.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • I think you just need to initialize `tm_hour`, `tm_min`, `tm_sec`, `tm_mon` and `tm_mday`. [Example](http://cpp.sh/3wti). +1 better safe than sorry. – Jonny Henly Apr 23 '16 at 05:21
  • `tm time_1 = {0};` is a complete initialization, but not a valid one. Although you won't have undefined behavior, `mktime()` will abort due to invalid inputs. When `mktime()` fails, it returns `-1`, and the difference between two `-1` is zero as observed by OP. – Ben Voigt Apr 23 '16 at 05:26
  • @BenVoigt when i tested saw mktime returned -1, what is wrong, what should i do? – Danial Razavi Apr 23 '16 at 05:31
  • @DanialRazavi: Make sure that all fields are inside the legal range that R Sahu described. In particular, notice that `tm_mday` ranges from 1-31 and cannot be zero. – Ben Voigt Apr 23 '16 at 05:32
  • @BenVoigt i checked, and i double checked with tm time_1 = {0, 0, 0, 1, 0, 0, 0, 0, 0}; too, but didn't fix. – Danial Razavi Apr 23 '16 at 05:45