Steveng
Steveng

Reputation: 51

Adjust Time to Daylight Saving for localtime C++

I have a piece of optimized function to get the GMT time. I would like to convert it to local time. I would want to call localtime and gmtime function only once to adjust the time to localtime as calling localtime and gmtime multiple times would defeat the purpose of using the optimized function. My idea is adding the difference in time zone to the GMT time I obtained. However, my problem is how could I adjust my localtime when there is daylight saving? Any ideas on checking that?

Thanks.

Upvotes: 5

Views: 3661

Answers (4)

ariscris
ariscris

Reputation: 533

You could call tzset() and then check the _daylight value.

Upvotes: 0

Jon Trauntvein
Jon Trauntvein

Reputation: 4554

My application has a need to obtain the local standard time (in the local time zone but not adjusted for daylight savings time). I'm not sure if this is exactly what you want but I believe the problem is similar. This is how I accomplish this myself. I know it to be portable between windows and linux:

  LgrDate rtn = local();
  int8 adjustment = 0;;
#ifdef _WIN32
  TIME_ZONE_INFORMATION zone_info;
  uint4 rcd;

  rcd = GetTimeZoneInformation(&zone_info);
  if(rcd == TIME_ZONE_ID_DAYLIGHT)
     adjustment = zone_info.DaylightBias*nsecPerMin;
#else
  // there is no portable means of obtaining the daylight savings time bias directly.  We can,
  // however, obtain the local time, and, if daylight savings time is enabled, we can use mktime
  // to find out what the bias would be.
  struct timeval time_of_day;
  struct tm local_tm;

  gettimeofday(&time_of_day,0);
  localtime_r(
     &time_of_day.tv_sec,
     &local_tm);
  if(local_tm.tm_isdst > 0)
  {
     local_tm.tm_isdst = 0;
     adjustment = (mktime(&local_tm) - time_of_day.tv_sec) * nsecPerSec * -1;
  }
#endif
  return rtn + adjustment;

Upvotes: 0

Amine Kerkeni
Amine Kerkeni

Reputation: 924

You could use TZ database that is stored most of the time in /usr/share/lib/zoneinfo in most linux distributions. This database manages daylight saving so you do not nees to deal with that.

Upvotes: 1

Peter G.
Peter G.

Reputation: 15114

You could work directly with a timezone database but perhaps you do not like to introduce another component.

If I followed your idea, I would store the time differences per week or day in advance and use them later. This is a bit dirty because you will lose the exact time of DST switches. For best precision you could in theory use a binary search on localtime but that seems way excessive compared to directly using a time zone database and what you arrive at here is in effect a time zone zone database entry for your time zone.

Upvotes: 0

Related Questions