go - 了解时间包的 golang 日期格式

标签 go time format

所以我的功能表现良好。

func Today()(result string){
    current_time := time.Now().Local()
    result =  current_time.Format("01/02/2006")
    return
}

打印 MM/DD/YYYY 而且我认为如果我在天数位置有一个大于 12 的值以明确它是 MM/DD/YYYY 会更易读所以我将其更改为以下内容

func Today()(result string){
    current_time := time.Now().Local()
    result =  current_time.Format("01/23/2004")
    return
}

令我懊恼的是,这导致了糟糕的结果。打印 MM/DDHH/DD0MM

意识到我的错误,我看到格式是由 reference time 定义的...

Mon Jan 2 15:04:05 -0700 MST 2006

我想知道这一刻是否有任何其他实例被用作日期时间的格式引用,以及这个引用时刻是否有昵称(如 null island )?

最佳答案

日期字符串中的值不是任意的。您不能只是将 02 更改为 03 并期望它起作用。日期格式化程序查找这些特定值,并知道 1 表示月份,2 表示月份中的日期,等等。

01/02/2006 更改为 01/23/2004 就像更改一个人类可读的表单,上面写着 First Name: ______ Last Name: ______ 到上面写着 First Name: ______ Ice Cream: ______ 的人。您不能期望任何人都知道 Ice Cream 应该表示 Last Name

名字

为此提供的唯一名称是“引用时间”,here :

Parse parses a formatted string and returns the time value it represents. The layout defines the format by showing how the reference time, defined to be

Mon Jan 2 15:04:05 -0700 MST 2006

here :

These are predefined layouts for use in Time.Format and Time.Parse. The reference time used in the layouts is the specific time:

Mon Jan 2 15:04:05 MST 2006

which is Unix time 1136239445. Since MST is GMT-0700, the reference time can be thought of as

01/02 03:04:05PM '06 -0700

To define your own format, write down what the reference time would look like formatted your way; see the values of constants like ANSIC, StampMicro or Kitchen for examples. The model is to demonstrate what the reference time looks like so that the Format and Parse methods can apply the same transformation to a general time value.

要说明您在谈论 Go 的引用时间,我会说“Go 的引用时间”。或者更明显地说,“Go 的时间。解析引用时间。”


顺便说一句,你的函数可以大大缩短:

func Today() string {
    return time.Now().Local().Format("01/02/2006")
}

关于go - 了解时间包的 golang 日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46167391/

相关文章:

go - 如何在不修改堆栈的情况下将表的内容转储到堆栈中?

regex - 处理由天,小时,分钟和秒定义的持续时间,例如R中的 “1d 3h 2m 28s”

python - 如何使用 pysimplegui 在新行中打印列表的每个元素?

list - FTP LIST命令返回的数据格式?

format - 猜测数据类型

go - 如何将接口(interface)转换为接口(interface) slice ?

同时进行 HTTP 和 RPC

sorting - 在 Golang 中使用 map

mysql - 如何读取MySQL时间?

javascript - 需要访问当前时间的嵌入式YouTube视频