4

I was using following code segment to calculate utc offset, but I realize sometimes it's returning wrong results:

double DateTime::getUTCOffset()
{
    time_t currtime;

    struct tm * timeinfo;



    time ( &currtime );

    timeinfo = gmtime ( &currtime );

    time_t utc = mktime( timeinfo );

    timeinfo = localtime ( &currtime );

    time_t local = mktime( timeinfo );



    // Get offset in hours from UTC

    double offsetFromUTC = ((difftime(local, utc) / HOUR_IN_SECONDS) );

    // Adjust for DST

    if (timeinfo->tm_isdst)
    {
        offsetFromUTC += 1;
    }
    return offsetFromUTC;
}

%90 of the time it's correct though, what's the best way of calculating utc offset?

erin c
  • 1,345
  • 2
  • 20
  • 36
  • 1
    Related: How to get the UTC offset with Boost DateTime: http://stackoverflow.com/questions/3854496/how-do-i-get-the-current-utc-offset-time-zone – Magnus Hoff Jul 13 '12 at 12:24

1 Answers1

7

I think the tm_gmtoff field should be available on you system.

std::time_t current_time;
std::time(&current_time);
struct std::tm *timeinfo = std::localtime(&current_time);
long offset = timeinfo->tm_gmtoff;
Nicolas Bachschmidt
  • 6,475
  • 2
  • 26
  • 36