Home >Backend Development >Golang >Convert 00:33 to duration in golang

Convert 00:33 to duration in golang

王林
王林forward
2024-02-06 08:24:11950browse

将 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

}

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

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

}

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete