Re: gmtime_r or strftime problem or just my code?????
On Apr 7, 7:42 pm, eskg...@gmail.com wrote:
I have this piece of code that takes a day of the year and
converts it to the month and day of month:
char start_mon[40];
char start_day[40];
int s_day = 84;
time_t daysecs = (s_day * 86400) - 1;
struct tm tm_result;
struct tm *tm_time = &tm_result;
tm_time = gmtime_r(&daysecs,&tm_result);
strftime(start_mon, sizeof(start_mon), (char*)"%m", tm_time);
strftime(start_day, sizeof(start_day), (char*)"%d", tm_time);
I am just testing it with 84, but this is a parameter to the
method. Anyway, the month and day should be 03 24, but I am
getting 03 25. It seems like it is not taking into account
leap year. Is it gmtime_r or strftime or something else? Do I
need to actually check the year and figure out if it is a leap
year?
I'm guessing that you're under a Unix or Unix-like system,
because of gmtime_r. If so, the date you are giving gmtime_r is
in 1970. 1970 wasn't a leap year, and the function is figuring
this out correctly.
Note that as a general rule, the only way to put a meaningful
value into a time_t is through one of the system functions. The
C/C++ standards say nothing about the representation of a
time_t. As far as you are concerned, it's a magic cookie.
Under Posix, of course, it's guaranteed to be the number of
seconds since the epoch, and I don't know of a Unix system where
the epoch is anything else but midnight, 1 Jan., 1970.
I was hoping there was something that would do that
automatically, but probably not.
I think it is doing it automatically. You gave it a time in
1970, and 1970 isn't a leap year.
If you want a particular day or whatever in this year, the way
to get it is:
std::time_t now = std::time( NULL ) ;
std::tm tmp = *std::localtime( &now ) ;
// modify tmp as desired...
std::time_t target = std::mktime( &tmp ) ;
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34