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.

Rza
  • 185
  • 1
  • 10
  • 2
    `time.Time` represents a full date and time. You're comparing two times on the same day. What you want is `12:00am` from the next day but you're not specifying a day at all. – Marc Sep 22 '21 at 05:32

1 Answers1

2

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

MenyT
  • 1,653
  • 1
  • 8
  • 19