Loading ...
Sorry, an error occurred while loading the content.

Getting timezone offset for any specified remote timezone wrt machine tz

Expand Messages
  • nee_savi
    Hi LBP members, I have been breaking my head for a day or 2 on this trivial issue of calcualting time offset between machine time and any specific timezone.
    Message 1 of 1 , Oct 26, 2009
    • 0 Attachment
      Hi LBP members,

      I have been breaking my head for a day or 2 on this trivial issue of calcualting time offset between machine time and any specific timezone.

      The catch is not to use setenv to set the TZ varaible. Though thats the easiest way to do it. But facing some issues in it.

      This is my code snippet


      bool calculateMachineToDestinationTimeOffset(const char* tz, long& offset)
      {
      assert(tz != NULL);

      if (GoUtil::validateTimeZone(tz) == false)
      {
      cout << GoEvent::Error << "Invalid TimeZone : " << tz << endl;
      return false;
      }

      char currentTimeZone[255];

      if (getenv("TZ") == NULL)
      {
      cout << GoEvent::Warning << "Can not get TimeZone information from environment" << endl;
      return false;
      }
      else
      {
      sprintf(currentTimeZone, "%s", getenv("TZ"));
      }

      time_t now = time(NULL);
      struct tm timeStruct;

      localtime_r(&now, &timeStruct);
      timeStruct.tm_isdst = -1;

      if (setenv("TZ", tz, 1) != 0)
      {
      cout<< GoEvent::Warning << "Fail to set TimeZone information" << endl;
      return false;
      }

      time_t then = mktime(&timeStruct);

      offset = now - then ;

      if (setenv("TZ", currentTimeZone, 1) != 0)
      {
      cout << GoEvent::Warning << "Fail to set TimeZone information" << endl;
      return false;
      }


      //Somehow the TZ is not set properly if getenv is not done in the end.
      //strange but .. I am doing it for the time being.

      cout << GoEvent::Info << "TimeZone is changed to:"<< getenv("TZ") <<endl;

      return true;
      }


      And immediately after calling this function I use the offset to get tick in destination and call localtime to get it into struct format.

      But somehow the last call to setenv dosent reset the TZ to original TZ and localtime_r is impacted.

      Any better way to do it???
    Your message has been successfully submitted and would be delivered to recipients shortly.