Today on Hugo Discourse, I came across the – Why “2006”? – question
regarding the use of {{ now.Format "2006" }}
in Hugo template. That
template simply prints the current year i.e. the time when that
template was rendered by Hugo.
As I was answering that, I thought that this was a good time to document this for myself too.. and thus this post.
Time.Format
Syntax #Hugo uses the Go Time.Format
method1 for formatting date and
time strings. But that format specification uses a strange syntax —
You need to associate 1, 2, 3, 4, 5, 6, 7 with date elements as
follows:
Number | Field Strings | Meaning |
---|---|---|
1 | 01 (with optional leading zero), 1, Jan, January | month |
2 | 02 (with optional leading zero), 2, Mon, Monday | day |
3 | 03 (with optional leading zero), 3, 15 | hour |
4 | 04 (with optional leading zero), 4 | minute |
5 | 05 (with optional leading zero), 5 | seconds |
6 | 06, 2006 | year |
-7 | -0700, -07:00, -07, MST | timezone |
n/a | PM (not AM) | AM or PM (uppercase) |
n/a | pm (not am) | am or pm (lowercase) |
n/a | anything else | shows up as it is |
You can visualize a formatting string "Jan 2 15:04:05 2006 MST"
as
below:
Jan 2 15:04:05 2006 MST
1 2 3 4 5 6 -7
dateFormat
#The dateFormat
accepts a date/time format using the same syntax.
Here is the signature of that function:
dateFormat "<FORMAT_STRING>" "<DATE_RFC3339>"
<FORMAT_STRING>
uses one or more date/time fields as shown in
the “Field Strings” column in Table 1. Few
examples:
<DATE_RFC3339>
is a date string compatible with RFC3339. Few
example valid date strings:
In addition, humanize
can be used to generate ordinal date, like
“1st”, “2nd”, “3rd”, ..
Go Formatting string | Output |
---|---|
"Jan 2 15:04:05 2006 MST" | "Jun 13 11:30:00 2018 EDT" |
"2006-01-02 03:04pm Monday" | "2018-06-13 11:30am Wednesday" |
"Jan 2, Mon" | "Jun 13, Wed" |
"It's 3 O'clock" | "It's 11 O'clock" |
((dateFormat "2" $dt) | humanize)
and (dateFormat "of
January" $dt)
:
Date ($dt ) |
Output |
---|---|
2018-06-01 | "1st of June" |
2018-06-02 | "2nd of June" |
2018-06-03 | "3rd of June" |
2018-06-04 | "4th of June" |
2018-06-10 | "10th of June" |
dateFormat
I am not a Go dev.. let me know if the correct term for that is
a “function” or a “method” in Go 😄. Update Time.Format
as a method. ↩︎