Skip to content
Permalink
Browse files
Add timezone support for front matter dates without one
Fixes #8810
  • Loading branch information
bep committed Jul 27, 2021
1 parent a57dda8 commit efa5760db5ef39ae084bfccb5b8f756c7b117a2a
@@ -11,7 +11,7 @@ menu:
docs:
parent: "functions"
keywords: [dates,time,location]
signature: ["time INPUT [LOCATION]"]
signature: ["time INPUT [TIMEZONE]"]
workson: []
hugoversion: "v0.77.0"
relatedfuncs: []
@@ -29,10 +29,12 @@ aliases: []

## Using Locations

The optional `LOCATION` parameter is a string that sets a default location that is associated with the specified time value. If the time value has an explicit timezone or offset specified, it will take precedence over the `LOCATION` parameter.
The optional `TIMEZONE` parameter is a string that sets a default time zone (or more specific, the location, which represents the collection of time offsets in a geographical area) that is associated with the specified time value. If the time value has an explicit timezone or offset specified, it will take precedence over the `TIMEZONE` parameter.

The list of valid locations may be system dependent, but should include `UTC`, `Local`, or any location in the [IANA Time Zone database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).

If no `TIMEZONE` is set, the `timeZone` from site configuration will be used.

```
{{ time "2020-10-20" }} → 2020-10-20 00:00:00 +0000 UTC
{{ time "2020-10-20" "America/Los_Angeles" }} → 2020-10-20 00:00:00 -0700 PDT
@@ -299,6 +299,9 @@ themesDir ("themes")
timeout (10000)
: Timeout for generating page contents, in milliseconds (defaults to 10 seconds). *Note:* this is used to bail out of recursive content generation, if your pages are slow to generate (e.g., because they require large image processing or depend on remote contents) you might need to raise this limit.

timeZone {{< new-in "0.86.0" >}}
: The time zone (or location), e.g. `Europe/Oslo`, used to parse front matter dates without such information and in the [`time` function](/functions/time/).

title ("")
: Site title.

@@ -14,6 +14,8 @@
package hugolib

import (
"fmt"
"strings"
"testing"
)

@@ -54,3 +56,133 @@ Date: {{ .Date | time.Format ":date_long" }}
b.AssertFileContent("public/nn/index.html", `Date: 18. juli 2021`)

}

func TestTimeZones(t *testing.T) {
b := newTestSitesBuilder(t)
b.WithConfigFile("toml", `
baseURL = "https://example.org"
defaultContentLanguage = "en"
defaultContentLanguageInSubDir = true
[languages]
[languages.en]
timeZone="UTC"
weight=10
[languages.nn]
timeZone="America/Antigua"
weight=20
`)

const (
pageTemplYaml = `---
title: Page
date: %s
lastMod: %s
publishDate: %s
expiryDate: %s
---
`

pageTemplTOML = `+++
title="Page"
date=%s
lastMod=%s
publishDate=%s
expiryDate=%s
+++
`

shortDateTempl = `%d-07-%d`
longDateTempl = `%d-07-%d 15:28:01`
)

createPageContent := func(pageTempl, dateTempl string, quoted bool) string {
createDate := func(year, i int) string {
d := fmt.Sprintf(dateTempl, year, i)
if quoted {
return fmt.Sprintf("%q", d)
}
return d
}

return fmt.Sprintf(
pageTempl,
createDate(2021, 10),
createDate(2021, 11),
createDate(2021, 12),
createDate(2099, 13), // This test will fail in 2099 :-)
)
}

b.WithContent(
// YAML
"short-date-yaml-unqouted.en.md", createPageContent(pageTemplYaml, shortDateTempl, false),
"short-date-yaml-unqouted.nn.md", createPageContent(pageTemplYaml, shortDateTempl, false),
"short-date-yaml-qouted.en.md", createPageContent(pageTemplYaml, shortDateTempl, true),
"short-date-yaml-qouted.nn.md", createPageContent(pageTemplYaml, shortDateTempl, true),
"long-date-yaml-unqouted.en.md", createPageContent(pageTemplYaml, longDateTempl, false),
"long-date-yaml-unqouted.nn.md", createPageContent(pageTemplYaml, longDateTempl, false),

// TOML
"short-date-toml-unqouted.en.md", createPageContent(pageTemplTOML, shortDateTempl, false),
"short-date-toml-unqouted.nn.md", createPageContent(pageTemplTOML, shortDateTempl, false),
"short-date-toml-qouted.en.md", createPageContent(pageTemplTOML, shortDateTempl, true),
"short-date-toml-qouted.nn.md", createPageContent(pageTemplTOML, shortDateTempl, true),
)

const datesTempl = `
Date: {{ .Date | safeHTML }}
Lastmod: {{ .Lastmod | safeHTML }}
PublishDate: {{ .PublishDate | safeHTML }}
ExpiryDate: {{ .ExpiryDate | safeHTML }}
`

b.WithTemplatesAdded(
"_default/single.html", datesTempl,
)

b.Build(BuildCfg{})

expectShortDateEn := `
Date: 2021-07-10 00:00:00 +0000 UTC
Lastmod: 2021-07-11 00:00:00 +0000 UTC
PublishDate: 2021-07-12 00:00:00 +0000 UTC
ExpiryDate: 2099-07-13 00:00:00 +0000 UTC`

expectShortDateNn := strings.ReplaceAll(expectShortDateEn, "+0000 UTC", "-0400 AST")

expectLongDateEn := `
Date: 2021-07-10 15:28:01 +0000 UTC
Lastmod: 2021-07-11 15:28:01 +0000 UTC
PublishDate: 2021-07-12 15:28:01 +0000 UTC
ExpiryDate: 2099-07-13 15:28:01 +0000 UTC`

expectLongDateNn := strings.ReplaceAll(expectLongDateEn, "+0000 UTC", "-0400 AST")

// TODO(bep) create a common proposal for go-yaml, go-toml
// for a custom date parser hook to handle these time zones.
// JSON is omitted from this test as JSON does no (to my knowledge)
// have date literals.

// YAML
// Note: This is with go-yaml v2, I suspect v3 will fail with the unquouted values.
b.AssertFileContent("public/en/short-date-yaml-unqouted/index.html", expectShortDateEn)
b.AssertFileContent("public/nn/short-date-yaml-unqouted/index.html", expectShortDateNn)
b.AssertFileContent("public/en/short-date-yaml-qouted/index.html", expectShortDateEn)
b.AssertFileContent("public/nn/short-date-yaml-qouted/index.html", expectShortDateNn)

b.AssertFileContent("public/en/long-date-yaml-unqouted/index.html", expectLongDateEn)
b.AssertFileContent("public/nn/long-date-yaml-unqouted/index.html", expectLongDateNn)

// TOML
// These fails: TOML (Burnt Sushi) defaults to local timezone.
// TODO(bep) check go-toml
// b.AssertFileContent("public/en/short-date-toml-unqouted/index.html", expectShortDateEn)
// b.AssertFileContent("public/nn/short-date-toml-unqouted/index.html", expectShortDateNn)
b.AssertFileContent("public/en/short-date-toml-qouted/index.html", expectShortDateEn)
b.AssertFileContent("public/nn/short-date-toml-qouted/index.html", expectShortDateNn)

}
@@ -22,6 +22,8 @@ import (
"sync"
"time"

"github.com/gohugoio/hugo/langs"

"github.com/gobuffalo/flect"
"github.com/gohugoio/hugo/markup/converter"

@@ -396,6 +398,7 @@ func (pm *pageMeta) setMetadata(parentBucket *pagesMapBucket, p *pageState, fron
BaseFilename: contentBaseName,
ModTime: mtime,
GitAuthorDate: gitAuthorDate,
Location: langs.GetLocation(pm.s.Language()),
}

// Handle the date separately
@@ -17,6 +17,7 @@ import (
"sort"
"strings"
"sync"
"time"

translators "github.com/bep/gotranslators"
"github.com/go-playground/locales"
@@ -71,10 +72,13 @@ type Language struct {
paramsMu sync.Mutex
paramsSet bool

// Used for date formatting etc. We don't want this exported to the
// Used for date formatting etc. We don't want these exported to the
// templates.
// TODO(bep) do the same for some of the others.
translator locales.Translator

locationInit sync.Once
location *time.Location
}

func (l *Language) String() string {
@@ -244,9 +248,25 @@ func (l *Language) IsSet(key string) bool {
return l.Cfg.IsSet(key)
}

func (l *Language) getLocation() *time.Location {
l.locationInit.Do(func() {
location, err := time.LoadLocation(l.GetString("timeZone"))
if err != nil {
location = time.UTC
}
l.location = location
})

return l.location
}

// Internal access to unexported Language fields.
// This construct is to prevent them from leaking to the templates.

func GetTranslator(l *Language) locales.Translator {
return l.translator
}

func GetLocation(l *Language) *time.Location {
return l.getLocation()
}
@@ -70,6 +70,9 @@ type FrontMatterDescriptor struct {

// This is the Page's Slug etc.
PageURLs *URLPath

// The Location to use to parse dates without time zone info.
Location *time.Location
}

var dateFieldAliases = map[string][]string{
@@ -119,17 +122,15 @@ func (f FrontMatterHandler) IsDateKey(key string) bool {
// A Zero date is a signal that the name can not be parsed.
// This follows the format as outlined in Jekyll, https://jekyllrb.com/docs/posts/:
// "Where YEAR is a four-digit number, MONTH and DAY are both two-digit numbers"
func dateAndSlugFromBaseFilename(name string) (time.Time, string) {
func dateAndSlugFromBaseFilename(location *time.Location, name string) (time.Time, string) {
withoutExt, _ := paths.FileAndExt(name)

if len(withoutExt) < 10 {
// This can not be a date.
return time.Time{}, ""
}

// Note: Hugo currently have no custom timezone support.
// We will have to revisit this when that is in place.
d, err := time.Parse("2006-01-02", withoutExt[:10])
d, err := cast.ToTimeInDefaultLocationE(withoutExt[:10], location)
if err != nil {
return time.Time{}, ""
}
@@ -370,7 +371,7 @@ func (f *frontmatterFieldHandlers) newDateFieldHandler(key string, setter func(d
return false, nil
}

date, err := cast.ToTimeE(v)
date, err := cast.ToTimeInDefaultLocationE(v, d.Location)
if err != nil {
return false, nil
}
@@ -388,7 +389,7 @@ func (f *frontmatterFieldHandlers) newDateFieldHandler(key string, setter func(d

func (f *frontmatterFieldHandlers) newDateFilenameHandler(setter func(d *FrontMatterDescriptor, t time.Time)) frontMatterFieldHandler {
return func(d *FrontMatterDescriptor) (bool, error) {
date, slug := dateAndSlugFromBaseFilename(d.BaseFilename)
date, slug := dateAndSlugFromBaseFilename(d.Location, d.BaseFilename)
if date.IsZero() {
return false, nil
}
@@ -53,7 +53,7 @@ func TestDateAndSlugFromBaseFilename(t *testing.T) {
expecteFDate, err := time.Parse("2006-01-02", test.date)
c.Assert(err, qt.IsNil)

gotDate, gotSlug := dateAndSlugFromBaseFilename(test.name)
gotDate, gotSlug := dateAndSlugFromBaseFilename(time.UTC, test.name)

c.Assert(gotDate, qt.Equals, expecteFDate)
c.Assert(gotSlug, qt.Equals, test.slug)
@@ -67,6 +67,7 @@ func newTestFd() *FrontMatterDescriptor {
Params: make(map[string]interface{}),
Dates: &resource.Dates{},
PageURLs: &URLPath{},
Location: time.UTC,
}
}

@@ -26,7 +26,7 @@ func init() {
if d.Language == nil {
panic("Language must be set")
}
ctx := New(langs.GetTranslator(d.Language))
ctx := New(langs.GetTranslator(d.Language), langs.GetLocation(d.Language))

ns := &internal.TemplateFuncsNamespace{
Name: name,

0 comments on commit efa5760

Please sign in to comment.