3

I am creating a form for QFIELD in a QGIS project.

I have three fields:

  • Date of today ([$now]), as a date format,
  • Number of months allocated for a certain task, as an integer
  • The due date for this task, as a date format too.

What expression should I write into the default box to compute the due date? I have tried many things without any success.

2
  • It is a) unclear, what fields you actually have and which you need to create, and b) unclear, what exactly you tried so far. Can you provide example data?
    – Erik
    Nov 19 '20 at 15:32
  • I have the fields: todaysdate (date), monthsnumber (int) and Finaldate (date). What i would like to achieve is, when i fill in QFIELD the todaysdate and monthsnumber, the box from Finaldate automatically update with the sume of todaysdate + months number. Ej, todays date = 20-11-202, monthsnumber = 4, finaldate (automatically)= 20-03-2020
    – Serggg182
    Nov 20 '20 at 8:17
7

You need to add an interval of time to the date. This interval can can be hard coded or read from another field

now() + to_interval('3 month')

oldDate + to_interval( myIntervalIntegerValue || ' month')

2
  • This solution seems to work perfectly, just comment that whenever you increment the namber of months, the days are dicreasing. Example, when I try to add 24 months to the actual date 20-11-2020 it genereates 10 days less 10-11-2022 instead of 20-11-2022. However, i find it a good solution.
    – Serggg182
    Nov 20 '20 at 9:08
  • @Serggg182 Yes, interval assumes every month is 30 days. If we print to_interval('12 month') we get 360 days only. Beware of to_interval('1 year') which is 365.25 days (effectively changing the hour). The most accurate solution would be to convert to a number of days (but then to simplify the number of days in February and the 30 - 31 days, you will come with an average of 30 days per month... back to original behavior :)
    – JGH
    Nov 20 '20 at 13:31
4

You can also use pyqgis:

from dateutil.relativedelta import * #https://stackoverflow.com/questions/35066588/is-there-a-simple-way-to-increment-a-datetime-object-one-month-in-python/35067328

lyr = QgsProject.instance().mapLayersByName('Refactored')[0] #Change to match your data
datefield = 'datefield' #Change
monthfield = 'months' #Change
duefield = 'Due_date' #Change

with edit(lyr):
    for f in lyr.getFeatures():
        newdate = QDate(f[datefield].toPyDate()+relativedelta(months=+f[monthfield]))
        f[duefield] = newdate
        lyr.updateFeature(f)

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.