2

I've a problem with following code:

QDateTime test2;
test2.setTime_t(25);
qDebug() << test2.toString("hh:mm:ss");

this prints "01:00:25" to output instead of 00:00:25. Why is the first hour set to 01 instead of 00 ?

I thought that maybe am/pm notation is used so i tried this

QDateTime test2;
test2.setTime_t(3600*22+25);
qDebug() << test2.toString("hh:mm:ss");

And still i received on output

"23:00:25"

Help :)

rohanpm
  • 4,264
  • 17
  • 16

2 Answers2

6

It's because you didn't set the QDateTime to UTC. So, 00:00:25 on Jan 1st 1970 in UTC time was probably 01:00:25 in your local timezone? And your code says "10:00:25" for me, at UTC+10 :)

Try this:

QDateTime test2;
test2.setTimeSpec(Qt::UTC);    
test2.setTime_t(25);
qDebug() << test2.toString("hh:mm:ss");
rohanpm
  • 4,264
  • 17
  • 16
  • Unfortunatelly it doesn't work :(. I tried all three options in setTimeSpec and hour is either 01 or 03. Maybe I have to set some other option ? –  Apr 06 '11 at 10:07
  • Did you use _exactly_ the code I pasted? If you e.g. put "AP" in your time string then that shifts the formatting from using 0-23 for hours, to using 1-12. – rohanpm Apr 06 '11 at 10:17
  • Ok I see the problem. This line test2.setTimeSpec(Qt::UTC); has to be put before test2.setTime_t(25); Works fine now :) –  Apr 06 '11 at 11:31
2

Just to add, it seems UTC is messing with you. Check the last line of the output:

#include <QCoreApplication>
#include <QDateTime>
#include <QDebug>

int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv );

    QDateTime test1;
    test1.setTime_t(25);
    qDebug() << "Local 1: " << test1.toString("hh:mm:ss");
    qDebug() << "Local 1: " << test1.toString();
    qDebug() << "UTC   1: " << test1.toUTC().toString();

    QDateTime test2;
    test2.setDate(QDate(1970,01,01));
    test2.setTime(QTime(00,59));
    qDebug() << "Local 2: " << test2.toString("hh:mm:ss");
    qDebug() << "Local 2: " << test2.toString();
    qDebug() << "UTC   2: " << test2.toUTC().toString();

    return 0;
}

Output:

Local 1:  "01:00:25" 
Local 1:  "Thu Jan 1 01:00:25 1970" 
UTC   1:  "Thu Jan 1 00:00:25 1970" 
Local 2:  "00:59:00" 
Local 2:  "Thu Jan 1 00:59:00 1970" 
UTC   2:  "Wed Dec 31 23:59:00 1969" 

PS: I'm at UTC + 1

Derick Schoonbee
  • 2,971
  • 1
  • 23
  • 39