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)

func main() {
   currentTime := time.Now()
   d, err := time.ParseDuration(currentTime.Format("15h04m05s"))
   if err != nil {
// 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?


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

import (

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


Answered By – Jaye Renzo Montejo

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.