Add timezone support for front matter dates without one

Fixes #8810
This commit is contained in:
Bjørn Erik Pedersen
2021-07-27 13:45:05 +02:00
parent a57dda854b
commit efa5760db5
10 changed files with 196 additions and 73 deletions

View File

@@ -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,7 +122,7 @@ 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 {
@@ -127,9 +130,7 @@ func dateAndSlugFromBaseFilename(name string) (time.Time, string) {
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
}

View File

@@ -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,
}
}