英文:
return formated time as string in Go
问题
我想在Go语言中以特定格式返回当前时间。我在格式化时间方面没有问题,但是当将其作为字符串返回时,遇到了问题:
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
英文:
I want to return the current time in a format in go, I have no trouble in format the time, but when return it as string in a func, I got stucked:
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"))
}
The out put is :
current Time is: 0x400c00
current Time is: 2015-01-16 12:45:33 +0800
instead of
current Time is: 2015-01-16 12:45:33 +0800
current Time is: 2015-01-16 12:45:33 +0800
which I expected.
答案1
得分: 3
在你的main
函数中,你应该使用getCurrentTime()
而不是getCurrentTime
。
像这样:
fmt.Println("当前时间是:", getCurrentTime())
当你将一个函数名作为参数传递时,你并没有调用它,实际上打印的是函数的地址。
英文:
In you main
function, you should use getCurrentTime()
instead of getCurrentTime
.
Like this:
fmt.Println("current Time is:", getCurrentTime())
When you pass a function name as the parameter, you are not calling it, the address of the function is actually printed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论