return formated time as string in Go

huangapple go评论75阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年1月16日 12:48:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/27977463.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定