英文:
Go time.Format wrong month
问题
我想根据文件的修改日期来重命名一些文件。
当我使用time.Format方法来获取正确的字符串时,基本上是按照YYYY-MM-DD_HH-MM-SS的格式,但日期中的天数有一个尾随的0。
我在这里做错了什么吗?
package main
import (
    "time"
    "fmt"
)
func main() {
    loc, _ := time.LoadLocation("Europe/Berlin")
    const layout = "2006-01-02_15-04-05"
    t := time.Date(2013, 07, 23, 21, 32, 39, 0, loc)
    fmt.Println(t)
    fmt.Println(t.Format(layout))
}
输出:
2013-07-23 21:32:39 +0200 CEST
2013-07-230_21-32-39
英文:
I'd like to rename some files based on their modification date.
When I use the time.Format method to get the correct string, basically in this format YYYY-MM-DD_HH-MM-SS, the day has a trailing 0.
Am I doing something wrong here?
package main
import (
    "time"
    "fmt"
)
func main() {
    loc, _ := time.LoadLocation("Europe/Berlin")
    const layout = "2006-01-20_15-04-05"
    t := time.Date(2013, 07, 23, 21, 32, 39, 0, loc)
    fmt.Println(t)
    fmt.Println(t.Format(layout))
}
Output:
<pre>2013-07-23 21:32:39 +0200 CEST
2013-07-230_21-32-39</pre>
答案1
得分: 6
你的layout没有使用参考日期:将其更改为"2006-01-02_15-04-05"
当你使用"2006-01-20_15-04-05"时,格式化程序会看到2,并将其用作日期,然后保留额外的0,因为它与参考日期的任何部分都不匹配。
英文:
Your layout isn't using the reference date: change it to  "2006-01-02_15-04-05"
When you use "2006-01-20_15-04-05", the formatter see the 2, and uses that for the day, then keeps the extra 0 since it doesn't match any part of the reference date.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论