Shion Ichikawa
Shion Ichikawa

Reputation: 33

How to extract only time as Duration

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?

Upvotes: 3

Views: 148

Answers (1)

Jaye Renzo Montejo
Jaye Renzo Montejo

Reputation: 1862

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))
}

Upvotes: 2

Related Questions