问题内容
我有一个字符串“12:34”,格式为“mm:ss”,我想将其转换为 time.duration。已经在这上面浪费了太多时间了。我在这段代码中做错了什么:
package main
import (
"fmt"
"strings"
"time"
)
func parseDuration(input string) (time.Duration, error) {
var layout string
if strings.Count(input, ":") == 1 {
layout = "04:05"
} else {
layout = "15:04:05"
}
t, err := time.Parse(layout, input)
if err != nil {
return 0, err
}
return t.Sub(time.Time{}), nil
}
func main() {
input := "00:04"
duration, err := parseDuration(input)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(int(duration.Seconds())) // I should get 4 but I get -31622396
}
登录后复制
https://go.dev/play/p/a-ehc-eptrd
正确答案
time 类型的零值是 1 年 1 月 1 日 00:00:00.000000000 utc。
func parseduration(input string) (time.duration, error) {
var layout string
if strings.count(input, ":") == 1 {
layout = "04:05"
} else {
layout = "15:04:05"
}
t, err := time.parse(layout, input)
if err != nil {
return 0, err
}
return t
}
fmt.println(time.time{})
// this prints 0001-01-01 00:00:00 +0000 utc
fmt.println(parseduration("00:04"))
// this prints 0000-01-01 00:00:04 +0000 utc
登录后复制
在您的情况下,您应该定义一个 start
对象,而不是直接使用 time.time{}
。例如,
package main
import (
"fmt"
"strings"
"time"
)
var origin = time.Date(0, 1, 1, 0, 0, 0, 0, time.UTC)
func parseDuration(input string) (time.Duration, error) {
var layout string
if strings.Count(input, ":") == 1 {
layout = "04:05"
} else {
layout = "15:04:05"
}
t, err := time.Parse(layout, input)
if err != nil {
return 0, err
}
return t.Sub(origin), nil
}
func main() {
input := "00:04"
duration, err := parseDuration(input)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(duration.String()) // this prints 4s
}
登录后复制
https://www.php.cn/link/bdf0f5f84843f08f00912ae5292162f6
以上就是将 00:33 转换为 golang 中的持续时间的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!