Qt ISODate formatted date/time including timezone

RobbieE picture RobbieE · Feb 24, 2014 · Viewed 14.5k times · Source

Does anyone know of a cleaner way to get the time zone included in the ISO string representation of a QDateTime?

I should be able to just use the following:

qDebug() << QDateTime::currentDateTime().toString(Qt::ISODate);

but this always comes out in UTC format:

2014-02-24T01:29:00Z

Currently, the way I'm working round this is to force the TimeSpec to be Qt::offsetFromUtc by explicitly setting the offset, which I'm getting from the QDateTime originally.

QDateTime now = QDateTime::currentDateTime();
int offset = now.offsetFromUtc();
now.setOffsetFromUtc(offset);
qDebug() << now.toString(Qt::ISODate);

This gives what was originally expected:

2014-02-24T01:29:00+02:00

Does anyone know how to do this in a cleaner way or must this be logged as a bug?

EDIT: I'm using Qt5.2.1

UPDATE:

The following small program shows what I mean:

#include <QtCore/QDateTime>
#include <QtCore/QDebug>

int main(int argc, int argv){
    qDebug() << QDateTime::currentDateTime().toString(Qt::ISODate);
    qDebug() << QDateTime::currentDateTime().toTimeSpec(Qt::OffsetFromUTC).toString(Qt::ISODate);

    QDateTime now = QDateTime::currentDateTime();
    int offset = now.offsetFromUtc();
    now.setOffsetFromUtc(offset);
    qDebug() << now.toString(Qt::ISODate);

    return 0;
}

The following output is generated:

"2014-02-24T10:20:49" 
"2014-02-24T08:20:49Z" 
"2014-02-24T10:20:49+02:00"

The last line is the one that is expected. Please note that the second time has been converted to UTC, which is not what is wanted.

Answer

lpapp picture lpapp · Feb 24, 2014

This had not been present before 5.2, but it was integrated in there. It seems that you got the syntax incorrect though because it should be like this:

QDateTime::currentDateTime().toTimeSpec(Qt::OffsetFromUTC).toString(Qt::ISODate)

as per the corresponding bugreport. Note that toTimeSpec(Qt::OffsetFromUTC) call in the middle.