小编dbe*_*que的帖子

在golang中解析日期和时间的最佳方法

我有很多日期时间值作为字符串传入我的golang程序.格式以位数固定:

2006/01/02 15:04:05
Run Code Online (Sandbox Code Playgroud)

我开始用time.Parse函数解析这些日期

const dtFormat = "2006/01/02 15:04:05"

func ParseDate1(strdate string) (time.Time, error) {
    return time.Parse(dtFormat, strdate)
}
Run Code Online (Sandbox Code Playgroud)

但我的节目有一些表演问题.因此,我尝试通过编写自己的解析函数来调整它,考虑到我的格式是固定的:

func ParseDate2(strdate string) (time.Time, error) {
    year, _ := strconv.Atoi(strdate[:4])
    month, _ := strconv.Atoi(strdate[5:7])
    day, _ := strconv.Atoi(strdate[8:10])
    hour, _ := strconv.Atoi(strdate[11:13])
    minute, _ := strconv.Atoi(strdate[14:16])
    second, _ := strconv.Atoi(strdate[17:19])

    return time.Date(year, time.Month(month), day, hour, minute, second, 0, time.UTC), nil
}
Run Code Online (Sandbox Code Playgroud)

最后我在这两个函数的基础上做了一个基准测试,得到了以下结果:

 BenchmarkParseDate1      5000000               343 ns/op
 BenchmarkParseDate2     10000000               248 ns/op
Run Code Online (Sandbox Code Playgroud)

这是性能提升了27%.在性能方面是否有更好的方法可以改善这种日期时间解析?

performance time parsing date go

6
推荐指数
2
解决办法
3884
查看次数

标签 统计

date ×1

go ×1

parsing ×1

performance ×1

time ×1