user666491
user666491

Reputation:

Qt4 problem with formatting hours in QDateTime

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 :)

Upvotes: 2

Views: 1907

Answers (2)

Derick Schoonbee
Derick Schoonbee

Reputation: 3021

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

Upvotes: 2

rohanpm
rohanpm

Reputation: 4274

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");

Upvotes: 6

Related Questions