使用时间包常量而不是数字。

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

go time package constants instead of digits

问题

Format函数中,可以使用常量代替数字吗?

time.Unix(1392899576, 0).Format(stdLongYear + "/" + stdZeroMonth + "/" + stdZeroDay)

而不是

time.Unix(1392899576, 0).Format("2006/01/02")

可以使用常量代替数字来构建日期格式字符串。

英文:

is it possible to use constants instead of digits in Format func

time.Unix(1392899576, 0).Format(stdLongYear +"/"+ stdZeroMonth +"/"+ stdZeroDay)

instead of

time.Unix(1392899576, 0).Format("2006/01/02")

答案1

得分: 2

你不能这样做。这些常量以小写字母开头,因此不能被导出。

模仿该包的唯一方法是要么复制它,要么在你自己的包中重新创建这些常量,如下所示:

package main

import (
	"fmt"
	"time"
)

const (
	stdLongYear  = "2006"
	stdZeroMonth = "01"
	stdZeroDay   = "02"
)

func main() {
	fmt.Println(time.Unix(1392899576, 0).Format(stdLongYear + "/" + stdZeroMonth + "/" + stdZeroDay))
}

点击这里可以查看示例代码。

英文:

No you cant. Those constant start with a lower case letter and thus are not exported.

the only way to mimic that package is to either copy it or to re-create the constants in your own package like below:

package main

import (
	"fmt"
	"time"
)

const (
	stdLongYear  = "2006"
	stdZeroMonth = "01"
	stdZeroDay   = "02"
)

func main() {
	fmt.Println(time.Unix(1392899576, 0).Format(stdLongYear + "/" + stdZeroMonth + "/" + stdZeroDay))
}

http://play.golang.org/p/wTwMLbheCM

huangapple
  • 本文由 发表于 2014年7月9日 01:47:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/24638405.html
匿名

发表评论

匿名网友

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

确定