How to Get the Difference in Hours Between Two Dates in Go

Created
Modified

Using time.Since Function

The time.Since() function returns the time elapsed since t. It is shorthand for time.Now().Sub(t). For example,

package main

import (
  "fmt"
  "time"
)

func main() {
  layout := "2006-01-02 15:04"

  v := "2022-05-09 10:00"
  t, err := time.Parse(layout, v)
  if err != nil {
    // panic()
  }

  duration := time.Since(t)
  fmt.Println(duration.Hours())
}
-2.5214217017602776

Using Sub Function

The Time.Sub() function returns the duration t-u. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, the maximum (or minimum) duration will be returned. To compute t-d for a duration d, use t.Add(-d).

package main

import (
  "fmt"
  "time"
)

func main() {
  layout := "2006-01-02 15:04"

  v := "2022-05-09 10:00"
  t, err := time.Parse(layout, v)
  if err != nil {
    // panic()
  }

  v = "2022-05-09 05:23"
  t2, err := time.Parse(layout, v)
  if err != nil {
    // panic()
  }

  duration := t2.Sub(t)
  fmt.Println(duration.Hours())
}
-4.616666666666667

Related Tags

#get# #hour# #date#