Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Time determination using QTime



  • Hi all.

    I'm making an app that works only during the period.
    Currently, the following code is used to determine if it is within the period.
    However, this method does not work well when the end time (endH) exceeds 0:00.

    What can I do to solve it?

    isIntime(int startH, int startM, endH, endM){
        QTime startHM(startH, startM);
        QTime endHM(endH, endM);
    
        if(QTime::currentTime() >= startHMm && QTime::currentTime() < endHM){
            return true;
        }
        else{
            return false;
        }
    }
    

    Thank you.


  • Lifetime Qt Champion

    Hi,

    Shouldn't you rather use QDateTime ?



  • @taku-s I would not use hours and minutes, but take the current unix timestamp QDateTime::currentDateTimeUtc().
    This should solve easely your issue.



  • Thank you, everyone.
    I think it was probably solved with the following code.
    Tonight I will see the result at 0: 5.

    isIntime(int startH, int startM,int endH, int endM){
        QTime startHM(startH, startM);
        QTime endHM(endH, endM);
        QDate today = QDate::currentDate();
        QDateTime startDHM(today, startHM);
        if(endHM < startHM){
            today = today.addDays(1);
        }
        QDateTime eDHM(today, endHM);
        if(QDateTime::currentDateTime() >= startDHM && QDateTime::currentDateTime() < endDHM){
            return true;
        }
        else{
            return false;
        }
    }


  • @taku-s Oh, I apologize, I have read too fast your post and misunderstand your request!

    isIntime(int startH, int startM,int endH, int endM){
        QTime startHM(startH, startM);
        QTime endHM(endH, endM);
        QTime currHM(QTime::currentTime());
    
        if(startHM <= endHM)
            return ((currHM >= startHM) && (currHM < endHM));
        return ((currHM >= startHM) || (currHM < endHM));
    }
    


  • Certainly, my code doesn't work
    Thank you



  • @taku-s Have you tested my proposition? There are conditions to ensure it can work:

    • startH and endH between 0 and 23 (inclusive)
    • startM and endM between 0 and 59 (inclusive)


  • OK
    I understard .

    Thank you.


Log in to reply