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!

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.

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

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

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

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

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

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.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor
