如何仅提取时间作为持续时间

huangapple go评论76阅读模式
英文:

How to extract only time as Duration

问题

我正在寻找一种从time.Time中提取时间为time.Duration的方法。

例如,
"2022-11-25 10:07:40.1242844 +0900 JST"(time.Time)
转换为
"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
}

这段代码可以工作,但它先将时间转换为字符串,然后再转换为持续时间,我认为这样做有点绕,我不喜欢这样。
有没有更好的方法来编写这段代码?

英文:

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?

答案1

得分: 2

另一种解决方案是将当前时间截断到当天的开始,然后使用time.Since()返回一个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))
}
英文:

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

huangapple
  • 本文由 发表于 2022年11月25日 09:11:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/74567494.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定