-
Notifications
You must be signed in to change notification settings - Fork 1
/
string.go
88 lines (74 loc) · 1.89 KB
/
string.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// SPDX-FileCopyrightText: 2023 Weston Schmidt <[email protected]>
// SPDX-License-Identifier: BSD-3-Clause
// Package approx provides a set of approximate duration units that extend the
// standard go package time.Duration.
package approx
import (
"errors"
"fmt"
"strings"
"time"
)
var (
Day = time.Hour * 24
Week = Day * 7
Year = Day * 365
)
var (
ErrInvalidDuration = errors.New("time: invalid duration")
)
// String converts a time.Duration into the larger approximate units for output.
// The default form is to prefix days, but weeks and years may be prepended, too.
// Passing a string with the options "d", "w", and "y" will enable each. Order
// and repeats are ignored.
func String(d time.Duration, format ...string) string {
var b strings.Builder
// Ensure the buffer doesn't have to grow more than once.
b.Grow(40)
format = append(format, "d")
withYears := strings.Contains(format[0], "y")
withWeeks := strings.Contains(format[0], "w")
withDays := strings.Contains(format[0], "d")
ns := int64(d)
if ns < 0 {
b.WriteString("-")
ns = -1 * ns
}
setSmaller := false
if withYears && ns >= int64(Year) {
years := ns / int64(Year)
ns -= years * int64(Year)
b.WriteString(fmt.Sprintf("%dy", years))
setSmaller = true
}
if withWeeks && ns >= int64(Week) {
weeks := ns / int64(Week)
ns -= weeks * int64(Week)
b.WriteString(fmt.Sprintf("%dw", weeks))
setSmaller = true
} else {
if withWeeks && setSmaller {
b.WriteString("0w")
}
}
if withDays && ns >= int64(Day) {
days := ns / int64(Day)
ns -= days * int64(Day)
b.WriteString(fmt.Sprintf("%dd", days))
setSmaller = true
} else {
if withDays && setSmaller {
b.WriteString("0d")
}
}
if setSmaller {
if ns < int64(time.Hour) {
b.WriteString("0h")
}
if ns < int64(time.Minute) {
b.WriteString("0m")
}
}
b.WriteString(time.Duration(ns).String())
return b.String()
}