dqwh0108
2015-01-16 04:48
浏览 210
已采纳

在Go中以字符串形式返回格式化日期

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.

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

我想以go的格式返回当前时间,我在格式时间上没有问题,但是当 返回它作为字符串在func中,我被卡住了:

 包main 
 
import(
“ fmt” 
“ time” 
)
 
func  getCurrentTime()string {
t:= time.Now()。Local()
返回fmt.Sprintf(“%s”,t.Format(“ 2006-01-02 15:04:05 +0800”))  
} 
 
func main(){
 fmt.Println(“当前时间为:”,getCurrentTime)
t:= time.Now()。Local()
 fmt.Println(“当前时间为:  “,t.Format(” 2006-01-02 15:04:05 +0800“))
} 
   
 
 

输出为:

 当前时间是:0x400c00 
当前时间是:2015-01-16 12:45:33 +0800 
   
 
 

而不是

 当前时间是:2015-01-16 12:45:33 +0800 
当前时间是:2015-01-16 12:45:33 +0800 \  n   
 
 

,这是我期望的。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • drpiqlzrh62917192 2015-01-16 04:52
    已采纳

    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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报