Skip to content

Commit 096feaa

Browse files
authored
performance improvement for parseDateTime (#1098)
1 parent f378f59 commit 096feaa

File tree

3 files changed

+48
-10
lines changed

3 files changed

+48
-10
lines changed

AUTHORS

+1
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ Vladimir Kovpak <cn007b at gmail.com>
9090
Xiangyu Hu <xiangyu.hu at outlook.com>
9191
Xiaobing Jiang <s7v7nislands at gmail.com>
9292
Xiuming Chen <cc at cxm.cc>
93+
Xuehong Chan <chanxuehong at gmail.com>
9394
Zhenye Xie <xiezhenye at gmail.com>
9495
Zhixin Wen <john.wenzhixin at gmail.com>
9596

utils.go

+4-10
Original file line numberDiff line numberDiff line change
@@ -113,20 +113,14 @@ func parseDateTime(str string, loc *time.Location) (t time.Time, err error) {
113113
if str == base[:len(str)] {
114114
return
115115
}
116-
t, err = time.Parse(timeFormat[:len(str)], str)
116+
if loc == time.UTC {
117+
return time.Parse(timeFormat[:len(str)], str)
118+
}
119+
return time.ParseInLocation(timeFormat[:len(str)], str, loc)
117120
default:
118121
err = fmt.Errorf("invalid time string: %s", str)
119122
return
120123
}
121-
122-
// Adjust location
123-
if err == nil && loc != time.UTC {
124-
y, mo, d := t.Date()
125-
h, mi, s := t.Clock()
126-
t, err = time.Date(y, mo, d, h, mi, s, t.Nanosecond(), loc), nil
127-
}
128-
129-
return
130124
}
131125

132126
func parseBinaryDateTime(num uint64, data []byte, loc *time.Location) (driver.Value, error) {

utils_test.go

+43
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"database/sql/driver"
1515
"encoding/binary"
1616
"testing"
17+
"time"
1718
)
1819

1920
func TestLengthEncodedInteger(t *testing.T) {
@@ -291,3 +292,45 @@ func TestIsolationLevelMapping(t *testing.T) {
291292
t.Fatalf("Expected error to be %q, got %q", expectedErr, err)
292293
}
293294
}
295+
296+
func TestParseDateTime(t *testing.T) {
297+
// UTC loc
298+
{
299+
str := "2020-05-13 21:30:45"
300+
t1, err := parseDateTime(str, time.UTC)
301+
if err != nil {
302+
t.Error(err)
303+
return
304+
}
305+
t2 := time.Date(2020, 5, 13,
306+
21, 30, 45, 0, time.UTC)
307+
if !t1.Equal(t2) {
308+
t.Errorf("want equal, have: %v, want: %v", t1, t2)
309+
return
310+
}
311+
}
312+
// non-UTC loc
313+
{
314+
str := "2020-05-13 21:30:45"
315+
loc := time.FixedZone("test", 8*60*60)
316+
t1, err := parseDateTime(str, loc)
317+
if err != nil {
318+
t.Error(err)
319+
return
320+
}
321+
t2 := time.Date(2020, 5, 13,
322+
21, 30, 45, 0, loc)
323+
if !t1.Equal(t2) {
324+
t.Errorf("want equal, have: %v, want: %v", t1, t2)
325+
return
326+
}
327+
}
328+
}
329+
330+
func BenchmarkParseDateTime(b *testing.B) {
331+
str := "2020-05-13 21:30:45"
332+
loc := time.FixedZone("test", 8*60*60)
333+
for i := 0; i < b.N; i++ {
334+
_, _ = parseDateTime(str, loc)
335+
}
336+
}

0 commit comments

Comments
 (0)