Convert 00:33 to duration in golang

王林
Release: 2024-02-06 08:24:11
forward
931 people have browsed it

将 00:33 转换为 golang 中的持续时间

Question content

I have a string "12:34" in the format "mm:ss" and I want to convert it to time. duration. Too much time has been wasted on this. What am I doing wrong in this code:

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

}
Copy after login

https://go.dev/play/p/a-ehc-eptrd


Correct answer


The zero value of time type is 1 year 1 month 1st 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
Copy after login

In your case, you should define a start object instead of using time.time{} directly. For example,

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

}

Copy after login

https://www.php.cn/link/bdf0f5f84843f08f00912ae5292162f6

The above is the detailed content of Convert 00:33 to duration in golang. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template