Convert a string to a time/datetime

Hi,

In my frontmatter, I have added two fields, start_at and stop_at


start_at: 08:00:00
stop_at: 12:00:00

In my template I would like to show the duration between stop_at and start_at

I tried with {{ time .Params.stop_at "15:04:05" }} because I wanted to convert the string to a time but the parser does not recognize the pattern (12:00:00 unable to parse date)

How can I do for.

  1. Convert the string to a time ?
  2. Compute the difference…

but I have not found a solution…

If you have an idea.

Thank you.

I have also tried with dateFormat and this other post Parsing dates in templates but I don’t find a solution…

{{ $myTime1 := printf "2000-01-01T%s" "08:00:00" | time }}
{{ $myTime2 := printf "2000-01-01T%s" "12:00:00" | time }}
{{ $myTime2.Sub $myTime1 }}

=>

4h0m0s
3 Likes

Interesting! I wasn’t aware of that function (and many others in that family)… needs to be documented.

I then found this online: https://gohugohq.com/howto/compare-date-strings-in-hugo/#calculations.

1 Like

HugoTemplateCodePlyGnd
(@kaushalmodi: not as good as your playground :slight_smile: )

1 Like

thank you