golang持续时间为字符串2h而不是2h0m0s

时间:2016-12-26 18:48:35

标签: string go time formatting duration

默认time.Duration字符串方法通过将def create @promo_code = @reward.promo_codes.new(promo_code_params) # code # code end 分钟和0s分钟数小时来格式化持续时间。是否有我可以使用的功能0m0s而不是5m5m0s代替2h ...或者我必须实现自己的功能?

2 个答案:

答案 0 :(得分:4)

不在标准库中,但创建一个很容易:

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
}

测试它:

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

输出(在Go Playground)上尝试:

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

答案 1 :(得分:2)

你可以像这样绕过持续时间:

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