return 在 Go 中将时间格式化为字符串

return formated time as string in Go

我想 return 在 go 中格式化当前时间,我在格式化时间方面没有问题,但是当 return 它作为 func 中的字符串时,我卡住了:

package main

import (
    "fmt"
    "time"
)

func getCurrentTime()string{
    t := time.Now().Local()
    return fmt.Sprintf("%s", t.Format("2006-01-02 15:04:05 +0800"))
}

func main() {
    fmt.Println("current Time is:",getCurrentTime)
    t := time.Now().Local()
    fmt.Println("current Time is:", t.Format("2006-01-02 15:04:05 +0800"))
}

输出是:

current Time is: 0x400c00
current Time is: 2015-01-16 12:45:33 +0800

而不是

current Time is: 2015-01-16 12:45:33 +0800
current Time is: 2015-01-16 12:45:33 +0800

如我所料。

在你的 main 函数中,你应该使用 getCurrentTime() 而不是 getCurrentTime。 像这样:

fmt.Println("current Time is:", getCurrentTime())

当你传递一个函数名作为参数时,你并不是在调用它,函数的地址实际上是打印出来的。