Howto add QTime to a QDateTime object?



  • Hi All,

    I have a QDateTime object, and I would like to add a QTime to it.

    How can I do this?

    kind regards,
    Cedric



  • @cdwijs

    Do I understand correctly that you want to set the time of a QDateTime object from a QTime object?

       QDateTime::setTime(const QTime &time)
    

    allows you to set the time



  • Hi The_,

    Almost. I have a QTimeEdit, and 2 QTimeDate Edits:
    QTimeEdit time;
    QTimeDate timedate1;
    QTimeDate timedate2;

    I would like to do this:
    timedate2 = timedate1 + time;

    Kind regards,
    Cedric



  • @cdwijs

    Maybe there is an easier way but you can calculate the miliseconds since start of day from your QTime and add it to the QDateTime then.

    datetime2 = datetime.addMSecs(time.msecsSinceStartOfDay());
    


  • Thanks. It works when I perform it in a few intermediate steps, but I get an error when I do it in one big step:
    '((MainWindow*)this)->MainWindow::twilightDurationEdit->QDateTimeEdit::time' does not have class type
    datetime = dateTimeEdit->dateTime().addMSecs(twilightDurationEdit->time.fromMSecsSinceStartOfDay());
    ^
    This code works:
    QDateTime datetime;
    QTime time;

    datetime = dateTimeEdit->dateTime();
    datetime = datetime.addDays(twilightDaysSpin->value());
    time = twilightDurationEdit->time();
    msecs = time.msecsSinceStartOfDay();
    datetime = datetime.addMSecs(msecs);

    This code doesn't compile:
    datetime = dateTimeEdit->dateTime().addMSecs(twilightDurationEdit->time.fromMSecsSinceStartOfDay());

    Kind regards,
    Cedric


  • Qt Champions 2016

    @the_, @cdwijs
    The problem is, QDateTime keeps both the date and the time of day, so is there a guarantee that QDateTime points to the same point in time from which QTime starts? I really doubt it.

    @cdwijs

    twilightDurationEdit->time.fromMSecsSinceStartOfDay()
    

    You are using a function (i.e. QDateTime::time) as a variable.
    The last should be:

    twilightDurationEdit->time().fromMSecsSinceStartOfDay()
    

    However, you consider the note my post starts with.


Log in to reply
 

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