问题
I am processing stored dates and times. I store them in a file in GMT in a string format
(i.e. DDMMYYYYHHMMSS
). When a client queries, I convert this string to a struct tm
, then convert it to seconds using mktime
. I do this to check for invalid DateTime. Again I do convert seconds to string format. All these processing is fine, no issues at all.
But I have one weird issue: I stored the date and time in GMT with locale also GMT. Because of day light saving, my locale time changed to GMT+1. Now, if I query the stored date and time I get 1 hour less because the mktime
function uses locale, i.e. GMT+1, to convert the struct tm
to seconds (tm_isdst
set to -1 so mktime
detects daylight savings etc. automatically).
Any ideas how to solve this issue?
回答1:
Use _mkgmtime/timegm as a complement to mktime
.
time_t mkgmtime(struct tm* tm)
{
#if defined(_WIN32)
return _mkgmtime(tm);
#elif defined(linux)
return timegm(tm);
#endif
}
回答2:
The Daylight Saving Time flag (tm_isdst) is greater than zero if Daylight Saving Time is in effect, zero if Daylight Saving Time is not in effect, and less than zero if the information is not available.
http://www.cplusplus.com/reference/ctime/tm/
回答3:
Here is the general algorithm:
- Pass your input to
mktime
. - Pass the output to
gmtime
. - Pass the output to
mktime
.
And here is a coding example:
struct tm input = Convert(input_string); // don't forget to set 'tm_isdst' here
time_t temp1 = mktime(&input);
struct tm* temp2 = gmtime(&temp1);
time_t output = mktime(temp2);
Note that function gmtime
is not thread-safe, as it returns the address of a static struct tm
.
来源:https://stackoverflow.com/questions/22557650/c-mktime-and-dst