Skip to content

Commit

Permalink
support parsing mixed %Z and %z
Browse files Browse the repository at this point in the history
  • Loading branch information
yoh2 committed Nov 20, 2022
1 parent dfc5f25 commit f0a3864
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
21 changes: 19 additions & 2 deletions parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ func parse(source, format string, loc, base *time.Location) (t time.Time, err er
var j, century, yday, colons int
var pm bool
var pending string
var hasZoneName, hasOffset bool
for i, l := 0, len(source); i < len(format); i++ {
if b := format[i]; b == '%' {
i++
Expand Down Expand Up @@ -178,7 +179,14 @@ func parse(source, format string, loc, base *time.Location) (t time.Time, err er
err = fmt.Errorf(`cannot parse %q with "%%Z"`, source[j:k])
return
}
loc = t.Location()
if hasOffset {
name, _ := t.Zone()
_, offset := locationZone(loc)
loc = time.FixedZone(name, offset)
} else {
loc = t.Location()
}
hasZoneName = true
j = k
case 'z':
if j >= l {
Expand Down Expand Up @@ -231,7 +239,12 @@ func parse(source, format string, loc, base *time.Location) (t time.Time, err er
j = k
}
}
loc, colons = time.FixedZone("", sign*((hour*60+min)*60+sec)), 0
var name string
if hasZoneName {
name, _ = locationZone(loc)
}
loc, colons = time.FixedZone(name, sign*((hour*60+min)*60+sec)), 0
hasOffset = true
case 'Z':
loc, colons, j = time.UTC, 0, j+1
default:
Expand Down Expand Up @@ -328,6 +341,10 @@ func parse(source, format string, loc, base *time.Location) (t time.Time, err er
return time.Date(year, time.Month(month), day, hour, min, sec, nsec, loc), nil
}

func locationZone(loc *time.Location) (name string, offset int) {
return time.Date(2000, time.January, 1, 0, 0, 0, 0, loc).Zone()
}

type parseFormatError byte

func (err parseFormatError) Error() string {
Expand Down
10 changes: 10 additions & 0 deletions parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -702,6 +702,16 @@ var parseTestCases = []struct {
format: "%Z",
parseErr: errors.New(`cannot parse "X" with "%Z"`),
},
{
source: "2020-07-24 23:14:15 +0530 (AAA)",
format: "%F %T %z (%Z)",
t: time.Date(2020, time.July, 24, 23, 14, 15, 0, time.FixedZone("AAA", (5*60+30)*60)),
},
{
source: "2020-07-24 23:14:15 (AAA) +0530",
format: "%F %T (%Z) %z",
t: time.Date(2020, time.July, 24, 23, 14, 15, 0, time.FixedZone("AAA", (5*60+30)*60)),
},
{
source: "01%02\t03\n450000",
format: "%H%%%M%t%S%n%f",
Expand Down

0 comments on commit f0a3864

Please sign in to comment.