Hugo: How to get the year off of a date object
Date: 2020-02-24 | hugo | date |
problem
I'm using Hugo to build my sites - I have the date of my page, but I only want to display the year part of that date. How can I display just the year part.
solution
We can use Hugo's built-in .Format
function to pull off different parts of a date. For year specifically, we use 2006
. I know that seems kinda arbitrary, and it is kinda, but there's some small logic in it as you can read in Hugo's official docs.
Now for the practical example - here's code that shows how to format your date object to just return year.
{{ range .Site.RegularPages }}
{{ $date = .Date }}
{{ $dateYear := ($date.Format "2006")}}
{{ end }}
Want more like this?
The best / easiest way to support my work is by subscribing for future updates and sharing with your network.