Testing for parseable date string

I have a yaml file containing metadata used around the site. One particular value usually contains a nicely formatted date string (YYYY-MM-DD), but in some cases it might contain pure text, like a fuzzy future date (early 2026, for example).

These dates are displayed in a couple of different formats, and Hugo is very helpful with that.

The problem I’m running into is that there seems to be no way for me to test whether a given string is parseable as a date. I’d like to do something like this:

{{ if (“early 2026” | time) }}
it worked
{{ else }}
it did not work
{{ end }}

But any attempt that direction throws an error:

execute of template failed at <time>: error calling time: unable to parse date: early 2026

One dumb workaround I thought of is to turn either the parseable date strings or the fuzzy strings into slices so that I can use reflect.IsSlice and handle them that way.

Is that my best option? Or is there a better way?

I just thought of an even dumber workaround: test if the string begins with a number, and if so, treat it as a date.

I don’t like it, but it will probably work for now.

Use the try statement, perhaps within a function:

layouts/_partials/functions/is-date.html

{{ $result := false }}
{{ with try (time.AsTime .) }}
  {{ with .Value }}
    {{ $result = true }}
  {{ end }}
{{ end }}
{{ return $result }}

Then call the function:

{{ $d := slice "2042-06-07" "early 2042" "07 Jun 2042" }}
{{ range $d }}
  {{ if partialCached "functions/is-date.html" . . }}
    {{ . | time.Format ":date_short" }}
  {{ else }}
    {{ warnf "%q is not a parsable date" . }}
  {{ end }}
{{ end }}

That’s the answer! That’s pretty much exactly what I was looking for. I should have thought to search the docs for “try”!

Thanks very much for the help.