英文:
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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论