Hugo: How to get the year off of a date object

Published: 2020-02-24 15:15:32 -0500 -0500

Reading time: 1 mins (120 words)

Tags: 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 }}

About the Ham

Hi I'm Hamilton and I wrote / built this! I like doing lots of things, but mostly I like to build (and then share those buildings). Some things I'm currently building: art, software, and prose. To stay up-to-date with my latest buildings, subscribe to my email list or follow one of my many other accounts. #buildit #shipit #justhamit

comments powered by Disqus