user2409054
user2409054

Reputation: 131

C++ mktime and DST

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?

Upvotes: 2

Views: 3087

Answers (3)

barak manos
barak manos

Reputation: 30136

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.

Upvotes: 1

dalle
dalle

Reputation: 18507

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
}

Upvotes: 8

JefGli
JefGli

Reputation: 791

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/

Upvotes: 1

Related Questions