Return values in time format

1

I have 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 the String() function does not include the "zeros" to the numbers because they are of type inteiro .

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

This challenge prevents you from using the date that is already built right into Go .

    
asked by anonymous 27.09.2017 / 17:16

1 answer

2

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

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

But, in this case you do not need strconv , you could use:

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

link

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

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

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

    return s
}

link

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

    
27.09.2017 / 21:14