2

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?

Søren Debois
  • 5,598
  • 26
  • 48
user2409054
  • 131
  • 1
  • 7

3 Answers3

8

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
}
dalle
  • 18,057
  • 5
  • 57
  • 81
  • Thanks for your answer, this might solve the problem. As of now every where mktime has been used for date operations but I will have to add new function to use mkgmtime for this specific purpose. – user2409054 Mar 21 '14 at 15:05
1

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/

JefGli
  • 781
  • 3
  • 15
  • My program will be used in different parts of the world, that's why tm_isdst set to -1 so mktime detects daylight savings automatically. – user2409054 Mar 21 '14 at 14:50
1

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.

barak manos
  • 29,648
  • 10
  • 62
  • 114