So I have a 2 Timber/Twig variables set to datenow
and dateborn
in WordPress that I want use to calculate a pets age in weeks and days like this: Your pet is now: 6 weeks and 3 days old! I wonder if anyone is up to writing this out for me on here – I would be tremendously grateful!!
FYI Thanks to: Twig date difference prints the correct number of days ie. 46 days for me but need to convert it now to 6 Weeks and 3 Days
{% set difference = date(datenow).diff(date(dateborn)) %}
{% set leftDays = difference.days %}
{% if leftDays == 1 %}
1 day
{% else %}
{{ leftDays }}
days
{% endif %}
2
Answers
Here below is what I finally was able to come up with which outputs what I want: Current age: 13 Weeks and 5 days old. (
dateborn
= April 1/21datenow
= July 6/21)But since I am so new at dev I still wonder if there would have been an easier/cleaner way of writing this, any thoughts anybody?
Try to keep your view files as clear as possible – no logic inside. Let’s create filter
Use it like
For example
today = 07.07.2021
You may consider to return full phrase from your filter if it is unnecessary or create function instead – it is up to you