downing1988
2018-10-23 05:58
浏览 301
已采纳

无法将time.Now()转换为字符串

I have this struct:

// Nearby whatever
type Nearby struct {
    id          int    `json:"id,omitempty"`
    me          int    `json:"me,omitempty"`
    you         int    `json:"you,omitempty"`
    contactTime string `json:"contactTime,omitempty"`
}

and then I call this:

strconv.Itoa(time.Now())

like so:

s1 := Nearby{id: 1, me: 1, you: 2, contactTime: strconv.Itoa(time.Now())}

but it says:

> cannot use time.Now() (type time.Time) as type int in argument to
> strconv.Itoa

does anyone know what that's about? I am trying to convert an int to a string here.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • donglinli2027 2018-10-23 06:48
    已采纳

    does anyone know what that's about? I am trying to convert an int to a string here.

    Time type is not equivalent to an int. If your need is a string representation, type Time has a String() method.

    Sample code below (also available as a runnable Go Playground snippet):

    package main
    
    import (
        "fmt"
        "time"
    )
    
    // Nearby whatever
    type Nearby struct {
        id          int
        me          int
        you         int
        contactTime string
    }
    
    func main() {
        s1 := Nearby{
            id:          1,
            me:          1,
            you:         2,
            contactTime: time.Now().String(), // <-- type Time has a String() method
        }
    
        fmt.Printf("%+v", s1)
    
    }
    

    Hope this helps. Cheers,

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题