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

无法将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,

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染