boom
boom

Reputation: 6166

retrieving time including time zone using ctime

I want to retrieve time zone from struct tm as the format below

2011-12-32 12:13:05 +0530(obtained using gtime)

I could get the first two sets but could not get the way getting the time zone value. Please let me know how it should get the time zone using c++ time.

Regards, iSight

Upvotes: 1

Views: 4716

Answers (2)

Aditya Kumar Pandey
Aditya Kumar Pandey

Reputation: 991

I think tm structure retrieved via time.h contains timezone information, if all you require is difference from GMT.

struct tm {
int tm_sec;     /* seconds after the minute [0-60] */
int tm_min;     /* minutes after the hour [0-59] */
int tm_hour;    /* hours since midnight [0-23] */
int tm_mday;    /* day of the month [1-31] */
int tm_mon;     /* months since January [0-11] */
int tm_year;    /* years since 1900 */
int tm_wday;    /* days since Sunday [0-6] */
int tm_yday;    /* days since January 1 [0-365] */
int tm_isdst;   /* Daylight Savings Time flag */
long    tm_gmtoff;  /* offset from CUT in seconds */
char    *tm_zone;   /* timezone abbreviation */

};

Something like the following can help:

    uint64_t diff;
{
    time_t secs = time (NULL);
    tm timeParts;
    memset(&timeParts, 0, sizeof(timeParts));
    tm *timeInfo = localtime_r( &secs, &timeParts );
    diff = mktime( timeInfo );

    memset(&timeParts, 0, sizeof(timeParts));
    timeInfo = gmtime_r ( &secs, &timeParts );
    diff -= mktime( timeInfo );
}
return diff;

Please note that this code does something else but it shows all the functions that you can use to retrieve information that you may require.

Upvotes: 0

Pavel Zhuravlev
Pavel Zhuravlev

Reputation: 87

If you really want to use standard C library to get timezone, try using external variable 'timezone' declared in time.h. Keep in mind that its value is set after tzset() function call. Every time conversion function that depends on the timezone implicitly calls this function. As an alternative you can call tzset() explicitly.

The 'timezone' variable should be declared like this in time.h:

extern long timezone;

It contains time difference between local time and UTC in seconds. Also you can use exern char* tzname[2] to get the symbolic timezone names for DST and non-DST periods.

You can not calculate the timezone information from struct tm directly, unless you know exactly the UTC time corresponding to time stored in that structure;

Upvotes: 2

Related Questions