Return values in time format

Asked

Viewed 370 times

1

I own a struct with 2 ints and I need to return these values in string but in time format.

type Clock struct {
    hour   int
    minute int
}

func New(hour, minute int) Clock {
    return Clock{hour, minute}
}

func (c Clock) String() string {
    return strconv.Itoa(c.hour) + ":" + strconv.Itoa(c.minute)
}

The return of function String() does not include the "zeros" due to the numbers as they are of the type inteiro.

retornado: "8:0", desejado "08:00"
retornado "10:3", desejado "10:03"

This challenge is to not use the date which already comes embedded just to the Go.

1 answer

2


A very simple way would be to add 0 to the left until there are two numbers, you have the fmt.Sprintf you can do this. If you use it it would look like:

func (c Clock) String() string {
    return fmt.Sprintf("%02v:%02v", strconv.Itoa(c.hour), strconv.Itoa(c.minute))
}

But you in this case don’t need the strconv, could use:

func (c Clock) String() string {
    return fmt.Sprintf("%02d:%02d", c.hour, c.minute)
}

https://play.golang.org/p/nQi80Yj_vh

There are several options, including a for like this extremely simple:

func lpad(s, value string, length int) string {

    for len(s) < length {
        s = value + s
    }

    return s
}

https://play.golang.org/p/02gfYXqxRx


Golang has the Time which can be used for timing issues, adding dates, times and also allows you to convert to string...

  • thanks, but the challenge says I can’t use the package time, I’m breaking my head to create the function Add() for seconds!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.