英文:
Golang Time parsing providing the format is returning wrong results
问题
我有一个 t time.Time
,我正在将其转换为特定的时区,并从中提取日期和时间(分别)作为字符串,如下所示:
日期应该是:2006-09-23
时间应该是:05:06:23
我正在进行以下操作:
- 将
t
设置为所需的时区:
var err error
loc, err := time.LoadLocation("America/Los_Angeles")
if err != nil {
return err
} else {
t = t.In(loc)
}
- 设置格式并将其转换为字符串,以便我可以提取其值:
format := "2006-01-02 15:03:04"
timestamp := t.Format(format)
timestampSlice := strings.Fields(timestamp)
fmt.Println(timestampSlice[0])
fmt.Println(timestampSlice[1])
但是我得到了意外的时间结果(日期正常工作):
当传递
time.Date(2021, time.Month(2), 21, 1, 10, 30, 0, time.UTC)
我期望的结果是
2021-02-20
和 17:10:30
但我得到的是:
时间为 17:05:10
当传递
time.Date(2022, time.Month(8), 26, 22, 7, 30, 0, time.FixedZone("Asia/Shanghai", 0))
我期望的结果是
2022-08-26
和 06:07:30
但我得到的是:
时间为 15:03:07
我做错了什么?传递给格式的值是否会影响解析?我认为格式只是指示结果应该如何显示的方式。
英文:
I've got a t time.Time
which I'm converting to an specific timezone and from which I need to extract both date and time (separately) as strings as follows:
Data should look like: 2006-09-23
Time should look like: 05:06:23
I'm doing the following:
- Setting
t
to the needed timezone:
var err error
loc, err := time.LoadLocation("America/Los_Angeles")
if err != nil {
return err
} else {
t = t.In(loc)
}
- Setting up the format and converting it to string so I can extract its values:
format := "2006-01-02 15:03:04"
timestamp := t.Format(format)
timestampSlice := strings.Fields(timestamp)
fmt.Println(timestampSlice[0])
fmt.Println(timestampSlice[1])
But I'm getting unexpected results for time (date works fine):
When passing
time.Date(2021, time.Month(2), 21, 1, 10, 30, 0, time.UTC)
I'd expect
2021-02-20
and 17:10:30
but I'm getting:
17:05:10
for the time
When passing
time.Date(2022, time.Month(8), 26, 22, 7, 30, 0, time.FixedZone("Asia/Shanghai", 0)),
I'd expect
2022-08-26
and 06:07:30
but I'm getting:
15:03:07
what am I doing wrong? does the values passed in the format have any effect in the parsing? I thought the format was only to signal the way the result should look
答案1
得分: 4
从文档中可以看到:
// Jan 2 15:04:05 2006 MST
// 1 2 3 4 5 6 -7
所以格式2006-01-02 15:03:04
将被解析为年-月-日 时-时-分
。注意,15
表示小时(00-23),03
表示小时(1-12),04
表示分钟。
因此,正确的格式应该是
format := "2006-01-02 15:04:05"
你可以在这里了解更多关于时间格式的信息:https://pkg.go.dev/time#example-Time.Format
英文:
From the docs:
// Jan 2 15:04:05 2006 MST
// 1 2 3 4 5 6 -7
So the format 2006-01-02 15:03:04
would be parsed as years-months-days hours-hours-minutes
. Note that 15
refers to the hours (00-23), that 03
refers to the hours (1-12), and 04
refers to the minutes.
So the correct format would be
format := "2006-01-02 15:04:05"
You can learn more about formatting time here: https://pkg.go.dev/time#example-Time.Format
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论