A Problem Using <ctime>

I am trying to get a date and time from the user and then store it into a tm struct. Then convert it into a time_t type for storage. When I need it again I want to convert the time_t type back into a tm struct and print it out or change it.

However when I do this it does not contain the same values that I first put into the tm struct. I believe the problem lies with mktime().

Below is a simplified version of my program. Am I doing something wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <ctime>

using namespace std;

int main(){
    tm t1, t2, t5, t6;
    time_t t3, t4;

    t1.tm_year = 2013 - 1900;
    t1.tm_mon = 1 - 1;
    t1.tm_mday = 31;
    t1.tm_hour = 6;
    t1.tm_min = 0;

    t2.tm_year = 2013 - 1900;
    t2.tm_mon = 1 - 1;
    t2.tm_mday = 31;
    t2.tm_hour = 10;
    t2.tm_min = 30;

    t3 = mktime(&t1);
    t4 = mktime(&t2);

    t5 = *localtime(&t3);
    t6 = *localtime(&t4);

    cout << asctime(&t1) << asctime(&t2);
    cout << asctime(&t5) << asctime(&t6);

    return 0;
}
Last edited on
I found out that I needed to set the tm_sec and tm_isdst members as well.

I also noticed that having two asctime() calls in the same cout statement goofs up. The second one will just print out the same thing the first one did. Can anyone tell me why?

Here is the working code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string>
#include <ctime>

using namespace std;

int main(){
    tm tm1, tm2, tm3, tm4;
    time_t t1, t2;

    tm1.tm_year = 2013 - 1900;
    tm1.tm_mon = 1 - 1;
    tm1.tm_mday = 31;
    tm1.tm_hour = 6;
    tm1.tm_min = 0;
    tm1.tm_sec = 0;
    tm1.tm_isdst = 0;

    tm2.tm_year = 2013 - 1900;
    tm2.tm_mon = 1 - 1;
    tm2.tm_mday = 31;
    tm2.tm_hour = 10;
    tm2.tm_min = 30;
    tm2.tm_sec = 0;
    tm2.tm_isdst = 0;

    t1 = mktime(&tm1);
    t2 = mktime(&tm2);

    tm3 = *localtime(&t1);
    tm4 = *localtime(&t2);

    cout << asctime(&tm3);
    cout << asctime(&tm4);

    return 0;
}
Last edited on
Topic archived. No new replies allowed.