Convert string to time.Duration

3,470 views
Skip to first unread message

vika...@gmail.com

unread,
Apr 3, 2022, 6:48:54 PM4/3/22
to golang-nuts
I am looking to convert a string (say 4) to type time.Duration.

I've looked around but could not find a way to do so.

package main

import (
    "fmt"
    "time"
)

func main() {
    // var addHours string = 4
    fmt.Println(time.Now().Local())
    timeAdd := time.Now().Local().Add(time.Hour * 4) // I want to use 4 from a string variable here
    fmt.Println(timeAdd)
}

peterGo

unread,
Apr 3, 2022, 7:56:10 PM4/3/22
to golang-nuts
func addHours(t time.Time, hours string) (time.Time, error) {
    i, err := strconv.ParseInt(hours, 10, 64)
    if err != nil {
        return time.Time{}, err
    }
    return t.Add(time.Hour * time.Duration(i)), nil
}


Peter

Amnon

unread,
Apr 4, 2022, 2:13:23 AM4/4/22
to golang-nuts
Use time.ParseDuration()

https://go.dev/play/p/SWUHBiSpflh

taylor

unread,
Apr 4, 2022, 10:13:46 AM4/4/22
to vika...@gmail.com, golang-nuts
Take a look at time.ParseDuration and its example: https://pkg.go.dev/time#ParseDuration
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.

vika...@gmail.com

unread,
Apr 4, 2022, 4:11:56 PM4/4/22
to golang-nuts
Thanks all for the hint and the snippets. I am all set now.
Reply all
Reply to author
Forward
0 new messages