search
HomeBackend DevelopmentGolangConvert 00:33 to duration in golang

将 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. If there is any infringement, please contact admin@php.cn delete
Logging Errors Effectively in Go ApplicationsLogging Errors Effectively in Go ApplicationsApr 30, 2025 am 12:23 AM

Effective Go application error logging requires balancing details and performance. 1) Using standard log packages is simple but lacks context. 2) logrus provides structured logs and custom fields. 3) Zap combines performance and structured logs, but requires more settings. A complete error logging system should include error enrichment, log level, centralized logging, performance considerations, and error handling modes.

Empty Interfaces ( interface{} ) in Go: Use Cases and ConsiderationsEmpty Interfaces ( interface{} ) in Go: Use Cases and ConsiderationsApr 30, 2025 am 12:23 AM

EmptyinterfacesinGoareinterfaceswithnomethods,representinganyvalue,andshouldbeusedwhenhandlingunknowndatatypes.1)Theyofferflexibilityforgenericdataprocessing,asseeninthefmtpackage.2)Usethemcautiouslyduetopotentiallossoftypesafetyandperformanceissues,

Comparing Concurrency Models: Go vs. Other LanguagesComparing Concurrency Models: Go vs. Other LanguagesApr 30, 2025 am 12:20 AM

Go'sconcurrencymodelisuniqueduetoitsuseofgoroutinesandchannels,offeringalightweightandefficientapproachcomparedtothread-basedmodelsinlanguageslikeJava,Python,andRust.1)Go'sgoroutinesaremanagedbytheruntime,allowingthousandstorunconcurrentlywithminimal

Go's Concurrency Model: Goroutines and Channels ExplainedGo's Concurrency Model: Goroutines and Channels ExplainedApr 30, 2025 am 12:04 AM

Go'sconcurrencymodelusesgoroutinesandchannelstomanageconcurrentprogrammingeffectively.1)Goroutinesarelightweightthreadsthatalloweasyparallelizationoftasks,enhancingperformance.2)Channelsfacilitatesafedataexchangebetweengoroutines,crucialforsynchroniz

Interfaces and Polymorphism in Go: Achieving Code ReusabilityInterfaces and Polymorphism in Go: Achieving Code ReusabilityApr 29, 2025 am 12:31 AM

InterfacesandpolymorphisminGoenhancecodereusabilityandmaintainability.1)Defineinterfacesattherightabstractionlevel.2)Useinterfacesfordependencyinjection.3)Profilecodetomanageperformanceimpacts.

What is the role of the 'init' function in Go?What is the role of the 'init' function in Go?Apr 29, 2025 am 12:28 AM

TheinitfunctioninGorunsautomaticallybeforethemainfunctiontoinitializepackagesandsetuptheenvironment.It'susefulforsettingupglobalvariables,resources,andperformingone-timesetuptasksacrossanypackage.Here'showitworks:1)Itcanbeusedinanypackage,notjusttheo

Interface Composition in Go: Building Complex AbstractionsInterface Composition in Go: Building Complex AbstractionsApr 29, 2025 am 12:24 AM

Interface combinations build complex abstractions in Go programming by breaking down functions into small, focused interfaces. 1) Define Reader, Writer and Closer interfaces. 2) Create complex types such as File and NetworkStream by combining these interfaces. 3) Use ProcessData function to show how to handle these combined interfaces. This approach enhances code flexibility, testability, and reusability, but care should be taken to avoid excessive fragmentation and combinatorial complexity.

Potential Pitfalls and Considerations When Using init Functions in GoPotential Pitfalls and Considerations When Using init Functions in GoApr 29, 2025 am 12:02 AM

InitfunctionsinGoareautomaticallycalledbeforethemainfunctionandareusefulforsetupbutcomewithchallenges.1)Executionorder:Multipleinitfunctionsrunindefinitionorder,whichcancauseissuesiftheydependoneachother.2)Testing:Initfunctionsmayinterferewithtests,b

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor