Gabriel Schreiber Gabriel Schreiber - 1 year ago 174
C Question

Distance UTC - LocalTime on Linux

I am writing a Linux (Ubuntu and Debian Lenny) application in C++.

Now I need to know the distance/offset between UTC and the currently set system time at a given day in the past. Since I need to convert recorded data, I the distance need to be calculated with respect to a date in the past (which may have a different DST setting than the current day).

Anyone know how to do this?

Edit: Reading the first answer I think I was misunderstood: I do not want to compare dates/times. I have date/time values which I want to convert from UTC to local time.

Answer Source

Prepare the tm structure with date:

struct tm date;
date.tm_year = year - 1900;
date.tm_mon = month - 1;
date.tm_mday = day;
date.tm_hour = hour;
date.tm_min = minute;
date.tm_sec = second;
date.tm_isdst = -1; // VERY IMPORTANT

mktime(&date); /// fill rest of fields

And then take a look on tm_gmtoff


This is distance from UTC.

Now this is Linux and BSD specific, it would not work on other stystems, and this works with respect to DST.

Read man mktime for more information. And filling struct tm with correct values

P.S.: Converting from UTC to Local and back?

time_t posix_time = timegm(&UTC_Filled_struct_tm); // Linux specific line

Local to UTC

time_t posix_time = mktime(&local_Filled_struct_tm);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download