QDateTime::toSecsSinceEpoch() seems not to work

1.2k views Asked by At

Some theory first:

According to the Qt Documentation the QDateTime::toSecsFromEpoch() function:

Returns the datetime as the number of seconds that have passed since 1970-01-01T00:00:00.000, Coordinated Universal Time.

and:

[...] for all valid dates, this function returns a unique value.

Here is the link to this specific function's description in Qt docs.

My implementation

Here are a few lines of code that are trying to utilize the capabilities of this function:

#include <QtCore>
#include <iostream>

int main()
{
    QDateTime* time = new QDateTime(QDateTime::currentDateTime());

    QString secs1 = QString::number(time->toSecsSinceEpoch());
    std::cout << secs1.toStdString() << std::endl;

    std::this_thread::sleep_for(std::chrono::milliseconds(10000));

    QString secs2 = QString::number(time->toSecsSinceEpoch());
    std::cout << secs2.toStdString();
}

Now, the secs1 and secs2 variables should contain different values, yet this is not the case... Here is the output of the program:

1601491247
1601491247

After waiting ten seconds the value of the secs2 should be different. I have no idea why it is not.

Can it be the case that the QDateTime object was initialized the wrong way? Or might it be some system dependent error? I've searched information related to my problem and found nothing. Please help.

2

There are 2 answers

1
JarMan On BEST ANSWER

QDateTime doesn't continually update. It stores a particular date and time. So no matter how long you wait, it will always give you the same value. To fix your code, you could do something like this:

    QDateTime time1 = QDateTime::currentDateTime();
    QString secs1 = QString::number(time1.toSecsSinceEpoch());
    std::cout << secs1.toStdString() << std::endl;

    std::this_thread::sleep_for(std::chrono::milliseconds(10000));

    QDateTime time2 = QDateTime::currentDateTime();
    QString secs2 = QString::number(time2.toSecsSinceEpoch());
    std::cout << secs2.toStdString();
0
ΦXocę 웃 Пepeúpa ツ On

"Now, the secs1 and secs2 variables should contain different values, yet this is not the case... "

no they dont...

QDateTime is not a clock, ist just a class to represent any given moment as a DateTime object.