When our server passes time/date values to clients, it does so in a formatted string representing the time in GMT (UTC). It's easy to get UTC from a CTime object with FormatGmt(), but there does not seem to be a way to put UTC back into another CTime object after we parse that string. Any time that I give to CTime seems to be interpreted as local time.
A clumbsy workaround is to store the original values of _timezone and _daylight (global variables in C runtime), set them to 0, construct my CTime object, then restore the variables. This works, but is ugly and obviously not threadsafe.
Can anyone offer a better alternative?
In short, I'm looking for a function like:
CTime GetCTimeFromGmt(int year, int month, int day, int hour, int minute, int second)
{
}
where the passed parameters are relative to GMT. The function must be thread safe.
Thanks,
Matthew
CTime GetCTimeFromGmt(int year, int month, int day, int hour, int minute, int second)
{
struct tm gmt_struct;
gmt_struct.tm_sec = second;
gmt_struct.tm_min = minute;
gmt_struct.tm_hour = hour;
ASSERT(day >= 1 && day <= 31);
gmt_struct.tm_mday = day;
ASSERT(month >= 1 && month <= 12);
gmt_struct.tm_mon = month - 1; // tm_mon is 0 based
ASSERT(year >= 1900);
gmt_struct.tm_year = year - 1900; // tm_year is 1900 based
gmt_struct.tm_isdst = -1; //DST is unknown
time_t gmt_tt = mktime(&gmt_struct);
// convert to gmt as though it was local time to get the offset
struct tm *reversed_offset_struct = gmtime( &gmt_tt );
time_t reversed_offset_tt = mktime(reversed_offset_str
time_t offset = reversed_offset_tt - gmt_tt;
time_t local_tt = gmt_tt - offset;
return CTime(local_tt);
}
My only concern now is the thread safety of gmtime(), which uses a static buffer. I think the MT CRT solves this, but I haven't been able to confirm one way or another.
I have to admit that I'm a bit surprised that neither CTime nor the C runtime offer a way to use GMT time as input!
Thanks for your help Migel. I want to give this a few days to see whether anyone can comment on the thread safety before I accept your answer.
-Matthew