我有一個字串“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 中的持續時間的詳細內容。更多資訊請關注PHP中文網其他相關文章!