C++ mktime and DST

本秂侑毒 提交于 2019-12-13 01:25:27

问题


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:

  1. Pass your input to mktime.
  2. Pass the output to gmtime.
  3. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!