tpl: Update Hugo time to support optional [LOCATION] parameter

This commit is contained in:
Mark Johnson
2020-10-19 15:58:05 -07:00
committed by Bjørn Erik Pedersen
parent b886fa46bb
commit 26eeb29147
4 changed files with 132 additions and 11 deletions

View File

@@ -31,13 +31,73 @@ type Namespace struct{}
// AsTime converts the textual representation of the datetime string into
// a time.Time interface.
func (ns *Namespace) AsTime(v interface{}) (interface{}, error) {
func (ns *Namespace) AsTime(v interface{}, args ...interface{}) (interface{}, error) {
t, err := cast.ToTimeE(v)
if err != nil {
return nil, err
}
return t, nil
if len(args) == 0 {
return t, nil
}
// Otherwise, if a location is specified, attempt to parse the time using the location specified.
// Note: In this case, we require the input variable to be a string for proper parsing.
// Note: We can't convert an existing parsed time by using the `Time.In()` as this CONVERTS/MODIFIES
// the resulting time.
switch givenType := v.(type) {
case string:
// Good, we only support strings
break
default:
return nil, fmt.Errorf("Creating a time instance with location requires a value of type String. Given type: %s", givenType)
}
location, err := _time.LoadLocation(args[0].(string))
if err != nil {
return nil, err
}
// Note: Cast currently doesn't support time with non-default locations. For now, just inlining this.
// Reference: https://github.com/spf13/cast/pull/80
fmts := []string{
_time.RFC3339,
"2006-01-02T15:04:05", // iso8601 without timezone
_time.RFC1123Z,
_time.RFC1123,
_time.RFC822Z,
_time.RFC822,
_time.RFC850,
_time.ANSIC,
_time.UnixDate,
_time.RubyDate,
"2006-01-02 15:04:05.999999999 -0700 MST", // Time.String()
"2006-01-02",
"02 Jan 2006",
"2006-01-02T15:04:05-0700", // RFC3339 without timezone hh:mm colon
"2006-01-02 15:04:05 -07:00",
"2006-01-02 15:04:05 -0700",
"2006-01-02 15:04:05Z07:00", // RFC3339 without T
"2006-01-02 15:04:05Z0700", // RFC3339 without T or timezone hh:mm colon
"2006-01-02 15:04:05",
_time.Kitchen,
_time.Stamp,
_time.StampMilli,
_time.StampMicro,
_time.StampNano,
}
for _, dateType := range fmts {
t, err := _time.ParseInLocation(dateType, v.(string), location)
if err == nil {
return t, nil
}
}
return nil, fmt.Errorf("Unable to ParseInLocation using date \"%s\" with timezone \"%s\"", v, location)
}
// Format converts the textual representation of the datetime string into