解析前后的时间是不同的。

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

The time is different before and after parsing with time.Parse

问题

我需要接收一个时间字符串,解析它,然后再次将其呈现为字符串:

package main

import ("fmt"; "time")

func main() {
  const timeLayout = "Mon, Jan 2, 2006 15:04 PM"
  sourceTime :=      "Mon, Apr 7, 2025 7:36 PM"
  myTime, err := time.Parse(timeLayout, sourceTime)
  if err != nil { panic(err) }
  fmt.Printf("\t\tsourceTime = \"%s\"\n myTime.Format(timeLayout) = \"%s\"\n",
    sourceTime, myTime.Format(timeLayout))
}

这是我期望的输出:

                sourceTime = "Mon, Apr 7, 2025 7:36 PM"
 myTime.Format(timeLayout) = "Mon, Apr 7, 2025 7:36 PM"

但我收到了这个奇怪的输出:

                sourceTime = "Mon, Apr 7, 2025 7:36 PM"
 myTime.Format(timeLayout) = "Mon, Apr 7, 2025 19:36 PM"

我没有改变变量中的任何内容,为什么我得到了相同布局的不同结果?我不应该改变这个时间布局。但我需要再次接收源字符串作为结果。

英文:

I need to receive a time as a string, parse it and then present it as a string again:

package main

import ("fmt"; "time")

func main() {
  const timeLayout = "Mon, Jan 2, 2006 15:04 PM"
  sourceTime :=      "Mon, Apr 7, 2025 7:36 PM"
  myTime, err := time.Parse(timeLayout, sourceTime)
  if err != nil { panic(err) }
  fmt.Printf("\t\tsourceTime = \"%s\"\n myTime.Format(timeLayout) = \"%s\"\n",
    sourceTime, myTime.Format(timeLayout))
}

It was my expected output:

                sourceTime = "Mon, Apr 7, 2025 7:36 PM"
 myTime.Format(timeLayout) = "Mon, Apr 7, 2025 7:36 PM"

But I received this strange output:

                sourceTime = "Mon, Apr 7, 2025 7:36 PM"
 myTime.Format(timeLayout) = "Mon, Apr 7, 2025 19:36 PM"

I did not change something in my variable, so why I received a different result with same layout? I should not change this time layout. But I need to receive the source string as a result again.

答案1

得分: 1

你的时间格式使用的是24小时制(例如15:04而不是3:04),所以当你进行格式化时,你得到的是19而不是7。如果你想要使用12小时制的时钟,那么你的时间格式应该是"Mon, Jan 2, 2006 3:04 PM"。

英文:

Your time layout is using a 24 hour clock (e.g. 15:04 instead of 3:04), so when you format it you get 19 instead of 7. If you want a 12 hour clock then your time layout should be "Mon, Jan 2, 2006 3:04 PM"

huangapple
  • 本文由 发表于 2023年4月14日 03:23:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76009121.html
匿名

发表评论

匿名网友

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

确定