golang字符串转时间间隔插件库go-str2duration的使用
Golang字符串转时间间隔插件库go-str2duration的使用
介绍
go-str2duration是一个可以将字符串转换为time.Duration的Go语言包。它支持以下字符串格式转换:
- 所有time.Duration返回的字符串格式
- 更易读的字符串格式,如"1w2d6h3ns"(1周2天6小时3纳秒)
- "µs"和"us"都表示微秒
它与Go标准库中的time.ParseDuration
功能相同,但增加了对天和周的支持。
安装
go get github.com/xhit/go-str2duration/v2
功能特性
- 支持所有time.Duration返回的字符串格式
- 支持更易读的字符串格式
- 支持微秒的两种表示方式(µs和us)
- 支持天和周的单位(1天=24小时)
使用示例
package main
import (
"fmt"
str2duration "github.com/xhit/go-str2duration/v2"
"time"
)
func main() {
// 测试各种时间字符串转换
for i, tt := range []struct {
dur string
expected time.Duration
}{
// 标准time.Duration字符串格式
{"1h", time.Duration(time.Hour)},
{"1m", time.Duration(time.Minute)},
{"1s", time.Duration(time.Second)},
{"1ms", time.Duration(time.Millisecond)},
{"1µs", time.Duration(time.Microsecond)},
{"1us", time.Duration(time.Microsecond)},
{"1ns", time.Duration(time.Nanosecond)},
{"4.000000001s", time.Duration(4*time.Second + time.Nanosecond)},
// 更易读的字符串格式
{"1ms1ns", time.Duration(time.Millisecond + 1*time.Nanosecond)},
{"1s20ns", time.Duration(time.Second + 20*time.Nanosecond)},
{"60h8ms", time.Duration(60*time.Hour + 8*time.Millisecond)},
// 支持天和周
{"2d3s96ns", time.Duration(48*time.Hour + 3*time.Second + 96*time.Nanosecond)},
{"1w2d3s96ns", time.Duration(168*time.Hour + 48*time.Hour + 3*time.Second + 96*time.Nanosecond)},
} {
durationFromString, err := str2duration.ParseDuration(tt.dur)
if err != nil {
panic(err)
}
// 检查解析结果是否符合预期
if tt.expected != durationFromString {
fmt.Println(fmt.Sprintf("index %d -> in: %s returned: %s\tnot equal to %s",
i, tt.dur, durationFromString.String(), tt.expected.String()))
} else {
fmt.Println(fmt.Sprintf("index %d -> in: %s parsed succesfully", i, tt.dur))
}
}
}
将Duration转换为字符串
你也可以使用String(t time.Duration)
函数将Duration转换为字符串。这个函数支持周和天,并且不会像Go标准库的t.String()
函数那样返回难看的十进制数。值为0的单位不会被返回。例如:"1d1ms"表示1天1毫秒。
注意事项
- 1天等于24小时
- 如果你不需要天和周的支持,可以直接使用Go标准库的
time.ParseDuration
更多关于golang字符串转时间间隔插件库go-str2duration的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复