0

The following seems to be odd. I am in central daylight savings time which is supposed to be offset -5 from UTC. When I output the string representation of the struct tm objects it looks correct. But however when I convert the struct tm's to time_t and I look at the values, I get a difference of 21600 which is 6 hours (21600 secs / 60 / 60 = 6 hours). I expect it to be 5 hours.

I am running Gcc 4.8.2 on Ubuntu 12.04.

 9      time_t t1 = time(nullptr);
 10     time_t t2 = t1;
 11     
 12     char buf1[64];
 13     char buf2[64];
 14     
 15     tm utcTm, localTm;
 16     tm* tmp;
 17     
 18     tmp = gmtime(&t1);
 19     utcTm = *tmp;
 20     
 21     tmp = localtime(&t2);
 22     localTm = *tmp;
 23     
 24     strftime(buf1, 64, "%c %Z", &utcTm);
 25     strftime(buf2, 64, "%c %Z", &localTm);
 26     
 27     cout << "UTC: " << buf1 << endl;
 28     cout << "local: " << buf2 << endl;
 29     
 30     cout << "Is DST? " << utcTm.tm_isdst << " " << localTm.tm_isdst << endl;
 31  
 32     time_t t3 = mktime(&utcTm);
 33     time_t t4 = mktime(&localTm);
 34  
 35     cout << "UTC: " << t3 << " Local: " << t4 <<  " Diff: " << (t3 - t4) << endl;
 36     cout << "Orig UTC: " << t3 << " Orig Local: " << t4 <<  " Diff: " << (t3 - t4) << endl;

Output:

UTC: Mon Jun 2 19:05:23 2014 GMT

local: Mon Jun 2 14:05:23 2014 CDT

Is DST? 0 1

UTC: 1401757523 Local: 1401735923 Diff: 21600

Nathan Doromal
  • 3,437
  • 2
  • 24
  • 25
  • Check the environment variable `TZ`: is it set for CST/CDT? Is the system time (`date` command) showing it correctly? – wallyk Jun 02 '14 at 19:10
  • It should be set. The date command gives me output "Mon Jun 2 14:12:09 CDT 2014". – Nathan Doromal Jun 02 '14 at 19:13
  • 1
    I think that the issue is that [mktime expects local time](http://pubs.opengroup.org/onlinepubs/009604599/functions/mktime.html). See also http://stackoverflow.com/q/11293422/862231 . For linux specific, you might be able to use timelocal and timegm http://linux.die.net/man/3/timegm – Dave S Jun 02 '14 at 20:11

0 Answers0