"Ernst Murnleitner" <> wrote in message news:<bf3cso$ak000$>...
> I am looking for a replacement of <ctime>.
>
> for the functions
>
> gmtime
> mktime
>
> One reason is, that these time functions use statically allocated memory but
> I want to use it in an multithreaded program.
On a POSIX system, you have functions like gmtime_r, mktime_r, etc.,
available, which take a pointer to storage rather than using static
storage. Versions of these are implemented as part of the tz library,
available here:
<http://www.twinsun.com/tz/tz-link.htm>
Parts of this package apparently are included as parts of most popular
Unix systems (e.g., every one I've used except AIX), plus DJGPP and
Cygwin, so you're already set on those platforms. If you're trying for
Visual C++ under Windows, this might at least give you a springboard
from which to work. (Perhaps you could coerce Cygwin to generate
MSVC-compatible DLLs for you?)
NB: This code has two header files. One is named "private.h" [for
obvious reasons], and the other doesn't prototype the relevant
functions. I made it work by doing it myself:
extern "C" {
void tzset (); /* call this first!! */
char *asctime_r (const struct tm *tm, char *buf);
char *ctime_r (const time_t *timep, char *buf);
struct tm *gmtime_r (const time_t *timep, struct tm *result);
struct tm *localtime_r (const time_t *timep, struct tm *result);
}
g++ -ansi -pedantic -Wall -Werror test.cpp -ltz
TZ='CST6CDT' ./a.out
Note also that you have to specify your time zone manually, either via
the TZ environment variable or an external time-zone file whose name
is compiled into the binary. Check the docs for more info on that.
> Another reason is, that mktime is not the reverse of gmtime (but of
> localtime).
Haven't seen one of those. However, you can do it yourself; see below.
> The only thing I need is: convert a time_t value into struct tm and back -
> but without daylight saving and time zones. The time should be in UTC.
>
> Unfortunately mktime uses the timezone (OK, I could set the timezone
> temporarily to GMT, but this is not clean).
>
> I think there is already an open source code somewhere? (The formula for
> converting struct tm into time_t would also be helpful).
<http://aa.usno.navy.mil/faq/docs/JD_Formula.html> supplies Fortran
code, easily convertible to C++, to convert between Julian and
Gregorian dates. One can convert time_t to Julian by dividing by the
number of seconds in a day and adding 2440588 (Julian for 1 Jan 1970);
the inverse will convert it back.
This code works great with GMT/UTC, but time zones are another mess
altogether. The ISO C time interface doesn't seem to know anything
about them except that some do daylight savings time on occasion; you
can't find out which one you're in or whether a particular date in
that zone was in daylight savings time at the time.
I guess that's what the tz library is for.
Good luck!
- Shane