Time duration to string 2h instead 2h0m0s

落爺英雄遲暮 提交于 2021-01-27 12:20:44

问题


The default time.Duration String method formats the duration with adding 0s for minutes and 0m0s for hours. Is there function that I can use that will produce 5m instead 5m0s and 2h instead 2h0m0s ... or I have to implement my own?


回答1:


Foreword: I released this utility in github.com/icza/gox, see timex.ShortDuration().


Not in the standard library, but it's really easy to create one:

func shortDur(d time.Duration) string {
    s := d.String()
    if strings.HasSuffix(s, "m0s") {
        s = s[:len(s)-2]
    }
    if strings.HasSuffix(s, "h0m") {
        s = s[:len(s)-2]
    }
    return s
}

Testing it:

h, m, s := 5*time.Hour, 4*time.Minute, 3*time.Second
ds := []time.Duration{
    h + m + s, h + m, h + s, m + s, h, m, s,
}

for _, d := range ds {
    fmt.Printf("%-8v %v\n", d, shortDur(d))
}

Output (try it on the Go Playground):

5h4m3s   5h4m3s
5h4m0s   5h4m
5h0m3s   5h0m3s
4m3s     4m3s
5h0m0s   5h
4m0s     4m
3s       3s



回答2:


You can just round the duration like this:

        func RountTime(roundTo string, value time.Time) string {
            since := time.Since(value)
            if roundTo == "h" {
                since -= since % time.Hour
            }
            if roundTo == "m" {
                since -= since % time.Minute
            }
            if roundTo == "s" {
                since -= since % time.Second
            }
            return since.String()
        }


来源:https://stackoverflow.com/questions/41335155/time-duration-to-string-2h-instead-2h0m0s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!