hugo icon indicating copy to clipboard operation
hugo copied to clipboard

Ability to parse time string with custom layout

Open BenSouchet opened this issue 1 year ago • 3 comments

The issue

Currently there is no way to parse date string(s) with custom layout, like the French one DD/MM/YYYY, the Spanish one DD-MM-YY, the Finnish one DD.MM.YYYY.

Proposal

A hugo time method to parse date string with a provided layout like this:

{{ time.ParseWithFormat FORMAT INPUT [TIMEZONE] }}

{{ time.ParseWithFormat "02/01/2006" "15/03/2021" }} → "2021-03-15T00:00:00Z"

How to

Internally this would use the Go time function ParseInLocation like this:

time.ParseInLocation("02/01/2006", "15/03/2021", loc)

Go Playground example: https://go.dev/play/p/gsSIgLgAYLL

BenSouchet avatar Jul 15 '22 10:07 BenSouchet

Currently there is no way to parse date string(s) with custom layout,

That's not entirely true. time.Format uses the location as defined per language in your site config.

We could consider adding a timeZone to time.Format, though. Would that work for you?

bep avatar Jul 15 '22 11:07 bep

Currently I cannot use time.Format with date input string like 15/03/2021.

If I want to convert a French date string to ISO 8601 format with time.Format, like this: {{ time.Format "2006-01-02" "15/03/2021" }} I get: error calling Format: unable to parse date: 15/03/2021

Even if in my config file I have set:

languageCode: "fr-FR"
defaultContentLanguage: "fr"
timeZone: "Europe/Paris"

This is why if we had the ability to pass the custom layout used by the date string we have, we could parse and convert it to ISO 8601 format.

BenSouchet avatar Jul 15 '22 11:07 BenSouchet

Idea: Maybe we could have an optional parameter to time.Format:

time.Format OUTPUT_LAYOUT INPUT [INPUT_LAYOUT]

then we could do:

{{ time.Format "2006-01-02" "15/03/2021" "02/01/2006" }} → "2021-03-15"

BenSouchet avatar Jul 15 '22 11:07 BenSouchet