Intelligent output of date range

In case it’s helpful to anyone, here’s a partial I made to display a date range accounting for differences in day, month, and year, where start_date and end_date are defined in frontmatter.

It will display date ranges with the following formats:

Jan 28-30, 2023 for dates with same month and year
Jan 28 - Feb 1, 2023 for dates with different month and same year
Dec 28, 2023 - Jan 1, 2024 for dates with different years

date_range.html:

{{ $start := .Params.start_date }}
{{ $end   := .Params.end_date }}
{{ $start_day := time.Format "2" $start }}
{{ $start_month := time.Format "Jan" $start }}
{{ $start_month_n := time.Format "1" $start }}
{{ $start_year := time.Format "2006" $start }}
{{ $end_day := time.Format "2" $end }}
{{ $end_month := time.Format "Jan" $end }}
{{ $end_month_n := time.Format "1" $end }}
{{ $end_year := time.Format "2006" $end }}

{{ if gt $end_year $start_year }}
  {{ $start_month}} {{ $start_day }}, {{ $start_year }} - {{ $end_month }} {{ $end_day }}, {{ $end_year }}
{{ else }}
    {{ if gt $end_month_n $start_month_n }}
        {{ $start_month}} {{ $start_day }} - {{ $end_month }} {{ $end_day }}, {{ $end_year }}
    {{ else }}
        {{ $start_month }} {{ $start_day }}-{{ $end_day }}, {{ $start_year }}
    {{ end }}
{{end}}

This is inspired by Intelligent output of date range in German, which does something similar but is complicated by the need to use non-English month names.

This is a quite common need for websites but is difficult to search for because the “range” keyword mostly gives results related to the Hugo function.

2 Likes