Search code examples
c++qtqtime

How to convert QTime 12 to 24 hr format and viceversa


I have QTime with current time displayed in screen and the time format I have to change based on selection 12/24. So how I can change the time 12/24 format of QTime.


Solution

  • It depends on how you get date or time from QTime. For example:

    QDateTime dateTime;
    dateTime = dateTime.currentDateTime();
    qDebug()<< dateTime.date().toString("dd.MM.yyyy");
    qDebug()<< dateTime.time().toString("H:mm:ss");
    qDebug()<< dateTime.time().toString("h:mm:ss ap");
    

    Output:

    "03.04.2018"
    "15:38:14"
    "3:38:14 pm"
    


    @Anonymouse I didn't get your question. you can get hour, minute, second separatly like this:

    qDebug()<< dateTime.time().toString("h");
    qDebug()<< dateTime.time().toString("mm");
    qDebug()<< dateTime.time().toString("ss");
    qDebug()<< dateTime.time().toString("ap");
    qDebug()<< dateTime.time().toString("h ap");
    qDebug()<< dateTime.time().toString("H ap");
    

    output:

    "14"
    "12"
    "15"
    "pm"
    "2 pm"
    "14 pm"