HUGO

Calculate difference in years

This is not a question rather than a tip for anyone else trying to do this very simple operation. I had a couple of places I wanted to show a difference in years. Both in relation to today but that is not necessary.

What you can use is a very small Hugo shortcode template. And instead of using separate shortcodes for each year calculation you can use a positional parameter.

So you call the shortcode in the markdown like this

He is {{% years-till-today 1972 %}} years old.

And in the shortcode file years-till-today.html:

{{ sub now.Year (.Get 0) }}

… and year.html

{{ now.Format "2006" }}

PS The calculation is a bit messy as it does not account for months of the year.

2 Likes