Important: Please read the Qt Code of Conduct -

Problem with QDateTime, setDate doesn't work properly

  • QDateTime tempDate = date;, (), 1);
    tempDate.time ().setHMS (0,0,0);
    int d1 = ().day ();

    I'm expecting value as 1 but it is returning original value of day in date.

  • Moderators

    because tempDate.time() and returns a copy time/data object.
    So altering these objects this way wont change anything on the tempDate object.

    Do this instead:

    QDateTime tempDate(date);
    tempDate.setDate( QDate(, (), 1) );
    tempDate.setTime( QTime(0,0,0) );
    int d1 = ().day ();

  • Hi @narinder83

    The problem is here:, (), 1);
    //       ^^^^^

    The QDateTime::date() function is declared const - it returns a new date object that no longer relates to the tempDate it came from. So, (), 1);

    is identical to:

    QDate date =;
    date.setDate(, (), 1);

    So you want to use QDateTime::setDate(), perhaps like:

    tempDate.setDate(QDate(, (), 1));


  • This:

    tempDate.setDate( QDate(, (), 1) );

    can be simplified into

    tempDate.addDays( 1 - );

  • said in Problem with QDateTime, setDate doesn't work properly:

    In this line happens the following: The function date() yields some result. This is temporary as you do not assign it to some variable. Then you change the temporary result with the setDate function. In the next line the temporary variable is lost together with your change.

    Later on you call the function date() again. It will which will return the same as in the first time, BUT of course without your change.

Log in to reply