Problem with QDateTime, setDate doesn't work properly



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

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


  • Moderators

    @narinder83
    because tempDate.time() and tempDate.date() 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(tempDate.date().year(), tempDate.date().month (), 1) );
    tempDate.setTime( QTime(0,0,0) );
    int d1 = tempDate.date ().day ();
    


  • Hi @narinder83

    The problem is here:

    tempDate.date().setDate(tempDate.date().year(), tempDate.date().month (), 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

    tempDate.date().setDate(tempDate.date().year(), tempDate.date().month (), 1);
    

    is identical to:

    QDate date = tempDate.date();
    date.setDate(tempDate.date().year(), tempDate.date().month (), 1);
    

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

    tempDate.setDate(QDate(tempDate.date().year(), tempDate.date().month (), 1));
    

    Cheers.



  • This:

    tempDate.setDate( QDate(tempDate.date().year(), tempDate.date().month (), 1) );
    

    can be simplified into

    tempDate.addDays( 1 - tempDate.date().day() );
    


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

    tempDate.date().setDate

    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
 

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