英文:
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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论