Вопрос

What is the difference between these two functions? It was my understanding that those should be the same: http://www.gnu.org/software/libc/manual/html_node/Broken_002ddown-Time.html.

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 timelocal with mktime 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 mktime adds 1 hour to the date I set?

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

On Linux Kubuntu instead, with both functions I get that an hour is added to both the tm 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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top