Aral Balkan

Mastodon icon RSS feed icon

Formatting an ISO 8601 date stamp in Hugo

Hugo has a plethora of functions that you can use in your templates, including one for formatting dates called dateFormat.

The index of this blog has a list of the posts in chronological order and uses a <time> tag. I wanted to include the machine-readable datetime attribute but the standard serialisation of Hugo’s .Date property doesn’t return an ISO 8601 timestamp. This led me to look up the esoteric syntax of Hugo’s dateFormat function and use the following format string to create an ISO 8601 string:

{{ $post.Date.Format "2006-01-02T15:04:05Z0700" }}

And here it is in use in the block that renders the posts for a given day (full source):

<ul> 
  {{ range $index, $post := .Pages }}
    <li>
      <time datetime="{{ $post.Date.Format "2006-01-02T15:04:05Z0700" }}">
        <span class='postdate day item-{{ $index }}'>{{ $post.Date.Format "Mon" }}</span>
      </time>
      <span class='postdate'>{{ $post.Date.Format "15:04" }}</span>
      <a href="{{ .RelPermalink }}">{{ $post.Title }}</a>
    </li>
  {{ end }}
</ul>