Home > Software design >  How to extract only time as Duration
How to extract only time as Duration

Time:11-25

I'm looking for a way to extract time from time.Time as time.Duration.

For instance, "2022-11-25 10:07:40.1242844 0900 JST"(time.Time) to "10h7m40s"(time.Duration)

func main() {
   currentTime := time.Now()
   d, err := time.ParseDuration(currentTime.Format("15h04m05s"))
   if err != nil {
      fmt.Println(err)
   }
   fmt.Print(d.String())
// 9h57m54s
}

This code works, but it once converts time to string and then converts to duration, which I think it is roundabout, and I don't like it. Is there a better way to write this code?

CodePudding user response:

Another solution is to truncate the current time to the start of day, then use time.Since() to return a Duration:

import (
  "fmt"
  "time"
)

func main() {
  now := time.Now()
  today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())

  fmt.Println(time.Since(today))
}
  •  Tags:  
  • go
  • Related