QGIS – Symbolize by Date Field Based on Current Date

dateqgissymbology

In QGIS 3.2.3: I have a layer/Shapefile with a date field (type DATE) that comes from a joined table. I would like to symbolize the points which are older than 10 days (based on the current date) in another color than points which are younger than 10 days (based on the current date). It would also be possible not to display the younger points.

Is there a way to use the current date to make such visualisations? Maybe with a rule based symbology: I thought in using an expression with the now() function, which returns the current date and time and then remove 10 days from it, but couldn't get it going. Am I missing something?

Best Answer

Try using a combination of age() (which calculates the difference between the first date minus the second date, and returns an interval) wrapped in day() (which converts the interval to days as a number).

So for example it is now 8 Nov 2018, 2:18 am. If my date field is 2018-10-25, I could find out the difference in days by doing:

day(age(now(),"date"))

which returns 14.09. In other words date was 14.09 days ago from now.

You may wish to wrap your now() variable in to_date() to make sure you are counting only whole days.

To style your points you would use a rule like day(age(to_date(now()),"date")) > 10 for dates that are more than 10 days before the current date, 0 < day(age(to_date(now()),"date")) =< 10 for dates that are between 0-10 days (inclusive of 10) before the current date.

Note that if you have a negative value for the expression before the operator it means your date is in the future.

edited to add: csk is right, you would need either a virtual field or an auto-updating field (see attribute field properties under Layer > Properties) for this to update whenever now() changes.

Related Question