dqteh7347
2016-04-12 22:23
采纳率: 100%
浏览 6.2k
已采纳

golang time.Now().Unix()文档与实现之间的差异?

这个链接https://golang.org/pkg/time/#Unix介绍了func Unix(sec int64, nsec int64) Time函数的签名含义, 还会返回一个time对象。

但是下面的程序中止了错误消息:

14: cannot use now.Unix() (type int64) as type time.Time in assignment`

func main() {
    var now time.Time
    now = time.Now()
    fmt.Println(now)

    var secs time.Time
    secs = now.Unix()
    fmt.Println(secs)
}

以下版本的程序生成输出:

func main() {
    var now time.Time
    now = time.Now()
    fmt.Println(now)

    // var secs time.Time
    secs := now.Unix()
    fmt.Println(secs)
}

2016-04-12 18:20:22.566965512 -0400 EDT

1460499622

这仅仅是文档中的错误吗?

图片转代码服务由CSDN问答提供 功能建议

https://golang.org/pkg/time/#Unix

声明此函数的签名为

   func Unix(sec int64,nsec int64)Time 
   
 
 

表示,它返回一个 Time 对象。 \ n

但是以下程序中止,并显示错误消息:

14:无法使用now.Unix()(类型为int64)作为时间类型。

  func main(){
 var now time.Time 
 now = time.Now()
 fmt.Println(  now)
 
 var secs time.Time 
 secs = now.Unix()
 fmt.Println(secs)
} 
   
 
 

版本的程序会产生输出

  func main(){
 var now time.Time 
 now = time.Now()
 fmt.Println(now)\  n 
 // var secs time.Time 
 secs:= now.Unix()
 fmt.Println(secs)
} 
   
 
 

2016-04-12 18:20:22.566965512 -0400 ED T

1460499622

这仅仅是文档中的错误吗? \ n

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duangua5742 2016-04-12 22:27
    已采纳

    The docs are correct, you're looking at the wrong version of Unix. The method you're using is this; https://golang.org/pkg/time/#Time.Unix it takes no arguments, is called on a time object and returns the unix time as an int64. The version you're referencing takes two arguments, both int64's, the seconds and nanoseconds? (not positive that's what the nseconds stands for) which represent a time in unix format and it returns a time.Time

    So to extend your second example;

    func main() {
        var now time.Time
        now = time.Now()
        fmt.Println(now)
    
        // var secs time.Time
        secs := now.Unix()
        fmt.Println(secs)
        t := time.Unix(secs, 0) // get a time from the seconds value which is a unix time
        fmt.Println(t)
    }
    

    Here's the above in play with one other line added to print the type of secs. https://play.golang.org/p/KksPPbQ1Jy

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题