I\'ve set up a C++ server/client environment, and am trying to send a time_t value from the server to the client (an useful thing in any server). But I\'m coming accross a heada
Update: There seems to be a library that provides exactly what you are looking for, check out Apache Portable Runtime, specifically this page on time routines. Other than that, I would say my answer still provides a way to implement this manually, provided all systems are POSIX.1-2001 compliant.
I'm having a similar problem right now and I think it might be nice to have some instructions on how to go through with this. Note that this solution here should be POSIX.1-2001 compatible (on Ubuntu 14.04, man tzset
and man localtime
gives such information, and I haven't used other sources, really).
Use localtime
to convert the data obtained from your call to time
into a struct tm
(see time.h
):
struct tm {
int tm_sec; /* seconds */
int tm_min; /* minutes */
int tm_hour; /* hours */
int tm_mday; /* day of the month */
int tm_mon; /* month */
int tm_year; /* year */
int tm_wday; /* day of the week */
int tm_yday; /* day in the year */
int tm_isdst; /* daylight saving time */
};
Note that localtime
will set the variable declared as (again, see time.h
)
extern long timezone; //seconds West of UTC
Since all types are now known, you can write your own conversion tool to make this data network-portable. Things to consider:
int
and long
have (use sizeof
, of course)struct tm
(use htonl
or htons
- for 64bit types, you will have to write your own) and send that information to the client (in whatever way you like).timezone
(see above).The client will then have to
struct tm
(if time zones are involved, write the received time zone data into a long
)long
and compute the time zone difference (compute the difference of the received timezone
datum and what you get by calling tzset
locally...), then adjust the struct tm
variable created in step 2.struct tm
adjusted to the client's local time zone, use mktime
to convert data back into a time_t