Luca Carlon Luca Carlon - 4 months ago 7x
Linux Question

Difference between mktime and timelocal

What is the difference between these two functions? It was my understanding that those should be the same:

I wrote this code to test the conversion (the Qt part is only for comparison):

#include <QCoreApplication>
#include <QDateTime>

int main(int argc, char *argv[])
QCoreApplication a(argc, argv);

QDateTime datetime(QDate(2012, 3, 25), QTime(5, 15));
qDebug("Timestamp: %lld.", datetime.toMSecsSinceEpoch()/1000L);

time_t timestamp;
tm* timeinfo = localtime(&timestamp);
timeinfo->tm_hour = 5;
timeinfo->tm_mday = 25;
timeinfo->tm_min = 15;
timeinfo->tm_mon = 2;
timeinfo->tm_year = 112;
timeinfo->tm_sec = 0;
qDebug("Timestamp: %ld.", timelocal(timeinfo));

return 0;

and found out that the output is:

Timestamp: 1332645300.
Timestamp: 1332645300.

which is what I'd expect. Then I replaced
and found out that this was the output:

Timestamp: 1332645300.
Timestamp: 1332648900.

It seems like an hour was added (consider that my current timezone is GMT+2:00 and my locale is set to Italy). Why? What is the difference between the two and why
adds 1 hour to the date I set?

EDIT: I tested again and it seems that on Mac OS X (and iOS)
is returning the same hour placed in the
structure, while
is actually adding an hour both in the returned
value and in the structure

On Linux Kubuntu instead, with both functions I get that an hour is added to both the
structure and the returned value.

Anyone who can explain why?


The man of OpenBSD's timelocal states:

timelocal is a deprecated interface that is equivalent to calling mktime() with a negative value for tm_isdst

A negative value for tm_isdst means that timelocal doesn't take daylight saving time (DST) into account. It seems that QDateTime has troubles with DST as well.
mktime on the other hand, handles DST and this might explain the 1-hour difference on OS X.

Since timelocal is deprecated, it might have newer imlementations that deal with DST properly.