I am building an application in C++ in which I need Time objects to give access to the current system time. To do this, I use time.h
. My two constructors go as follow:
Time::Time(bool p_daylightSavingEnabled /* = true */)
{
time_t rawTime = time(nullptr);
struct tm* timeInfo = localtime(&rawTime);
timeInfo->tm_isdst = static_cast<int>(p_daylightSavingEnabled);
m_hours = timeInfo->tm_hour;
m_minutes = timeInfo->tm_min;
m_seconds = timeInfo->tm_sec;
}
Everything is pretty straight forward except for the use of the tm_isdst
flag which I added because a unit test fails when the hour changes, but still is mysterious to me. I have found no clear documentation on how to properly use this flag on the Internet and I have heard that on some systems, it is not even available (i.e. set to 0).
Is this a correct way to use tm_isdst
and if not, how should it be used (for example in such a constructor) to work properly across different systems?
Clarification: For now, I am not interested in any alternatives of time.h
.
Your code should be simply:
Finding out what time it is "now" does not require you to tell the machine whether DST is on or off. It already knows.
P.S.: Your code is thread-unsafe for no reason--use
localtime_r()
instead to fix this.