转换00:33至golang持续时间

cigdeys3  于 2023-02-06  发布在  Go
关注(0)|答案(2)|浏览(157)

我有一个字符串“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

ni65a41a

ni65a41a1#

时间类型的零值为1年1月1日00:00:00.00000000 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://go.dev/play/p/maGeyA0KWd3

4xrmg8kj

4xrmg8kj2#

问题在于行返回值t.Sub(time.Time{}),nil。您要从t中减去time.Time的零值,这相当于从t中减去Unix纪元时间。
要从字符串中获取持续时间,应改用time.ParseDuration():

duration, err := time.ParseDuration(input)
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println(int(duration.Seconds()))

这将正确地解析字符串中的持续时间,并且您将得到预期的输出4。

相关问题