Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ mktime and DST

Tags:

c++

mktime

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?

like image 241
user2409054 Avatar asked Dec 09 '25 09:12

user2409054


2 Answers

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
}
like image 176
dalle Avatar answered Dec 11 '25 23:12

dalle


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/

like image 20
JefGli Avatar answered Dec 11 '25 23:12

JefGli