时间持续时间转换为字符串,将2小时转换为”2h”而不是”2h0m0s”。

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

Time duration to string 2h instead 2h0m0s

问题

默认的time.Duration String方法会在分钟后添加0s,在小时后添加0m0s来格式化持续时间。是否有可以使用的函数,可以生成5m而不是5m0s,以及2h而不是2h0m0s...或者我必须自己实现这个功能?

英文:

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

得分: 13

前言: 我在github.com/icza/gox发布了这个实用程序,请参阅timex.ShortDuration()


虽然标准库中没有,但创建一个很容易:

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
英文:

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

得分: 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()
}

这段代码会根据指定的精度对时间进行四舍五入,并返回结果。

英文:

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

huangapple
  • 本文由 发表于 2016年12月27日 02:48:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/41335155.html
匿名

发表评论

匿名网友

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

确定