1st of all, time_t is 'long unsigned', so your second printf()'s output is faulty. You should always compile with at least '-Wall' to detect those errors.
Thanks for this tip. The compiler here reported time_t as long int. Using %li in the printf() the values for unix_time look better now !
]]>Thanks. Yes that's correct.
Then I can correct it by simply doing:
int unix_time_corr = unix_time+3600;
However, mktime seems to be limited to 1900-?? or so... so eventually I'll have to find another solution for this...
This is all a bit intransparent to me.
For example when I use str_time.tm_year = 1300 - 1900; The year 1300.
unix_time is 331760832, which is wrong. That's OK cause it's outside the range of mktime (1900-..).
But then ctime returns: Fri Jan 1 12:00:00 1300, the correct year. How is this possible ?
1st of all, time_t is 'long unsigned', so your second printf()'s output is faulty. You should always compile with at least '-Wall' to detect those errors.
As to why ctime() is returning correct date. My 1st suggestion is to read the man pages carefully.
tm members are "int"s. So, they can accept negative values. ctime(t) is is equivalent to asctime(localtime(t)).
My guess is that localtime(t) internally casts t to a signed value. And then assigns correct values to tm members. If that's the case. Then what's passed to asctime() is correct.
]]>Then I can correct it by simply doing:
int unix_time_corr = unix_time+3600;
However, mktime seems to be limited to 1900-?? or so... so eventually I'll have to find another solution for this...
This is all a bit intransparent to me.
For example when I use str_time.tm_year = 1300 - 1900; The year 1300.
unix_time is 331760832, which is wrong. That's OK cause it's outside the range of mktime (1900-..).
But then ctime returns: Fri Jan 1 12:00:00 1300, the correct year. How is this possible ?
To learn C/C++ I'm trying to make a little space calculator.
First I would like to calculate the julian date of a given date. Using the Unix time this should be fairly simple.
(Ignoring calendar changes etc. for now.)
This is what I did so far:
// Setting the time manually
struct tm str_time;
time_t unix_time; // (time in seconds from 1. Jan 1970 00:00:00 GMT)
str_time.tm_year = 1970 - 1900; // (years from 1900)
str_time.tm_mon = 1 - 1; // (month starting at 0)
str_time.tm_mday = 1;
str_time.tm_hour = 00;
str_time.tm_min = 00;
str_time.tm_sec = 00;
str_time.tm_isdst = 0;
unix_time = mktime(&str_time);
printf("Given time is: %s\n", ctime(&unix_time));
printf("Unix time: %i s\n", unix_time);
ctime returns the correct given date Jan 1 00:00:00 1970.
But the unix_time is -3600.
Why is there an error of 1h/Shouldn't the unix_time be 0 ?
Is it wrong to initialize tm this very simple way ?
]]>