PDA

View Full Version : QDateTime UTC Time_t problem



scieck
6th February 2012, 05:04
Hello,
shouldn't line 2 and line 4 below print the same UTC time?
Line 2 prints the correct UTC time, but line 4 prints local time.

The variable utc is holding UTC time, then calling utc.toTime_t() should return number of seconds from epoch to UTC, is this right ?
Then on line 4, a new QDateTime is built using the number of seconds from epoch to UTC, so shouldn't this print UTC time again?



QDateTime utc = QDateTime::currentDateTimeUtc();
qDebug() << utc;
uint time = utc.toTime_t();
qDebug() << QDateTime::fromTime_t(time); // this prints local time which is UTC + 9 hours


output:


QDateTime("Mon Feb 6 04:00:48 2012")
QDateTime("Mon Feb 6 13:00:48 2012")

ChrisW67
6th February 2012, 06:32
Line 2 and 4 do print the same time, i.e they have the same time_t value which is always UTC, they are just formatted for different time zones.

QDateTime::fromTime_t() returns a QDateTime set to the local time corresponding to specified seconds after the epoch, i.e. it has Qt::LocalTime as its time spec, and this drives the string representation.

Try this:


qDebug() << "Local:" << QDateTime::currentDateTime();
QDateTime utc = QDateTime::currentDateTimeUtc();
qDebug() << "UTC:" << utc;
uint time = utc.toTime_t();

QDateTime result(QDate(), QTime(), Qt::UTC); // a null UTC time
result.setTime_t(time);
qDebug() << "Result:" << result;



Local: QDateTime("Mon Feb 6 15:29:30 2012")
UTC: QDateTime("Mon Feb 6 05:29:30 2012")
Result: QDateTime("Mon Feb 6 05:29:30 2012")

scieck
6th February 2012, 07:47
I see, thanks Chris,

as I feel that local time is a special case of UTC time, I would have used Qt::UTC as (default) time spec rather than Qt::LocalTime.

anyway thanks for the clarification
cheers