2
votes

I am using clock_gettime() in my C++ program to get the current time. However, the return value is seconds since epoch in UTC. This code can get messed up in my time zone during daylight savings when the time shifts by one hour.

The system itself has NTP syncing it to always give the correct time in EST. Is there a way to get clock_gettime() to report the local time instead of UTC so I can avoid the daylight savings issue?

4
Why don't you just convert from UTC to local time? Separate "getting the time" from "converting to local time".Jon Skeet
Sure, but then I have to change the conversion factor twice a year manually in my code.user788171
I wasn't suggesting hard-coding it. I was suggesting using a date/time library which was time zone aware to perform the conversion.Jon Skeet
Also consider using the cctz library to do the conversions.Matt Johnson-Pint

4 Answers

2
votes

Realize that time also reports seconds since the beginning of 1970 (in a time_t). If you take the tv_sec member of the timespec and pass it to localtime or localtime_r, you should get what you want.

timespec tsv;
clock_gettime(CLOCK_REALTIME, &tsv);
time_t t = tsv.tv_sec; // just in case types aren't the same
tm tmv;
localtime_r(&t, &tmv); // populate tmv with local time info

And you can deal with the tv_nsec member of the timespec however you wish.

1
votes

If you are using Windows, you can use this GetTimeZoneInformation, but you have to include the Windows API.

Another methode to achieve this would be the struct tm. You will find the details here: struct tm. "The Daylight Saving Time flag (tm_isdst) is greater than zero if Daylight Saving Time is in effect, zero if Daylight Saving Time is not in effect, and less than zero if the information is not available." I think this is the easier way.

0
votes

If you are able to use Boost, you can control all of this explicitly by using the date time libraries: http://www.boost.org/doc/libs/1_49_0/doc/html/date_time.html

I've had to deal with time on a variety of platforms and in a variety of languages, and I find the boost libraries wildly superior to anything else available.

0
votes
#include <time.h>
time_t rawtime;
struct tm *timeinfo;

    time(&rawtime);
    timeinfo = localtime(&rawtime);
    if (timeinfo->tm_isdst)
        Hour -= 1; // daylight savings time