Calculate the Closest Time Difference in HH:MM(am/pm) Format using Go

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

Calculate the Closest Time Difference in HH:MM(am/pm) Format using Go

问题

我在计算从下午到上午或相反方向的时间差时遇到了一点问题。例如:

ref, _ := time.Parse("03:04pm", "11:59pm")
t, _ := time.Parse("03:04am", "12:00am")

fmt.Println(t.Sub(ref).Minutes()) // 得到的结果是-719,我期望得到1(分钟)

实际上,这是正确的,但我想要得到最小的差异。

英文:

I got a bit problem when calculating the time difference from PM to AM or vice versa. For instance:

ref, _ := time.Parse("03:04pm", "11:59pm")
t, _ := time.Parse("03:04am", "12:00am")

fmt.Println(t.Sub(ref).Minutes()) // Got -719, my expectation is 1 (minutes)

Actually that's true, but I want to get the smallest difference.

答案1

得分: 2

你得到-719的原因是你没有提供日期信息,并且在第二个time.Parse中,你的模板中有一个拼写错误。模板必须包含pm

time.Parse("03:04pm", "11:59pm") // 0000-01-01 23:59:00 +0000 UTC
time.Parse("03:04am", "12:00am") // 0000-01-01 12:00:00 +0000 UTC

你需要提供日期信息和模板中的pm

time.Parse("02 03:04pm", "01 11:59pm") // 0000-01-01 23:59:00 +0000 UTC
time.Parse("02 03:04pm", "02 12:00am") // 0000-01-02 00:00:00 +0000 UTC

参考链接:https://stackoverflow.com/a/69338568/12301864

英文:

The reason you got -719 is that you do not provide date information and in second time.Parse you have typo in template. Template has to contain pm

time.Parse("03:04pm", "11:59pm") // 0000-01-01 23:59:00 +0000 UTC
time.Parse("03:04am", "12:00am") // 0000-01-01 12:00:00 +0000 UTC

You need to provide day information and pm in template

time.Parse("02 03:04pm", "01 11:59pm") // 0000-01-01 23:59:00 +0000 UTC
time.Parse("02 03:04pm", "02 12:00am") // 0000-01-02 00:00:00 +0000 UTC

see https://stackoverflow.com/a/69338568/12301864

huangapple
  • 本文由 发表于 2021年9月22日 11:46:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/69277941.html
匿名

发表评论

匿名网友

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

确定