Substract two QString values



  • Hi,
    I´m trying to substract two hours.
    QString hour_1 = "11:00";
    QString hour_2 = "10:00";

    I would like to save the result from (11:00 - 10:00) into another QString.

    ¿Does anyone know how could I do this?

    Thanks for replying!


  • Lifetime Qt Champion

    Hi,

    Do you mean

    QString result = hour_1 + " - " + hour_2;
    

    ?



  • Hey,

    I think that you want to compute the difference between the two timestamps ?
    Take a look at QTime (http://doc.qt.io/qt-5/qtime.html) and don't use QString. I think you should try to use a suitable type for your var.
    Two solutions :

    • Either you get a time from QString so you can try something like this :

    // Time in QString
    QString sHour_1 = "11:00";
    QString sHour_2 = "10:00";

    // Time in QTime from QString
    QTime hour_1 = QTime::fromString(sHour_1, "hh:mm");
    QTime hour_2 = QTime::fromString(sHour_2, "hh:mm");

    // hour_2 in seconds to substracts from hour_1
    int secs = hour_2.second();

    QTime result = hour_1.addSecs(-secs); // minus 'cause secs is positive

    result.toString("hh:mm"); // will get you a QString "01:00"

    • Or you could have taken the times in QTime from the beginning :

    QTime hour_1 (11, 0, 0);
    QTime hour_2 (10, 0, 0);

    Then you do the same as above.

    Gruz



  • I did this:

    QTime hour_1 = QTime::fromString(sHour_1,"hh:mm");
    QTime hour_2 = QTime::fromString(sHour_2,"hh:mm");
    
    qDebug()<<hour_2;
    
    int secs = hour_2.second();
    
    qDebug()<<secs;
    
    QTime result = hour_1.addSecs(-secs);
    QString result2 =result.toString("hh:mm");
    
    qDebug()<<result;
    qDebug()<<result2;
    
    

    But the result obtained is this:
    "11:00"
    "10:00"
    QTime("10:00:00.000")
    0
    QTime("11:00:00.000")
    "11:00"

    Sorry for my English.



  • Can you match every qDebug with the line please ?
    (np for the english mine is bad too)



  • @Gruzzyh2

    qDebug()<<sHour_1;
    "11:00"

    qDebug()<<sHour_2;
    "10:00"

    qDebug()<<hour_2;
    QTime("10:00:00.000")

    qDebug()<<secs;
    0

    qDebug()<<result;
    QTime("11:00:00.000")

    qDebug()<<result2;
    "11:00"


  • Lifetime Qt Champion

    A more simpler solution:

        QTime time1 = QTime::fromString("11:00", "HH:mm");
        QTime time2 = QTime::fromString("10:00", "HH:mm");
    
        qDebug() << QTime::fromMSecsSinceStartOfDay(time2.msecsTo(time1));
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.