Important: Please read the Qt Code of Conduct -

Question about QDateTime

  • I'm trying to construct QDateTime instance and can't figure out what am I doing wrong.
    Both QDate and QTime instances are valid, but when I construct QDateTime with Qt::LocalTime, QDateTime is invalid, while if spec is Qt::UTC, everything is fine. What is going on there?
    btw, I'm using Qt 5.5.1
    Here is the code:

    // let's set the date and time and check if
    // they're valid
    QDate d(2007, 3, 25);
    qDebug()<<"date: "<<d.toString("yyyy-MM-dd");
    if(d.isValid()) { qDebug()<<"TIME is Valid";}
    QTime t(2,30, 0);
    qDebug()<<"time: "<<t.toString("HH:mm:ss");
    if(t.isValid()) { qDebug()<<"TIME is Valid";}
    // Let's construct QDateTime with Qt::LocalTime
        QDateTime dt(d,t);
        qDebug()<<"dt: "<<dt.toString("yyyy.MM.dd HH:mm:ss");
        qDebug()<<"time zone"<<dt.timeZone();
    // Another way, but with Qt::UTC
        QDateTime dt(d,t, Qt::UTC);
        qDebug()<<"UTC dt: "<<dt.toString("yyyy.MM.dd HH:mm:ss");
        qDebug()<<"time zone"<<dt.timeZone();

  • According to the docs in QDateTime::IsValid:

    • If the timeSpec() is Qt::LocalTime or Qt::TimeZone then the date and time are checked to see if they fall in the Standard Time to Daylight Time transition hour, i.e. if the transition is at 2am and the clock goes forward to 3am then the time from 02:00:00 to 02:59:59.999 is considered to be invalid.

    QDateTime specified for March 25th, 2007 from 02:00:00 to 02:59:59.999 falls into a " Standard Time to Daylight Time transition hour", i.e. QDateTime::isValid fails, which in turn means that that time does not exist for timeSpec() Qt::LocalTime or Qt::TimeZone.
    Sorry for using this forum as a rubber duck...

Log in to reply