Skip to content

Commit 392834f

Browse files
molivierianlancetaylor
authored andcommitted
time: add examples for Duration functions
Change-Id: I78f4ec32c6445015ce626a552edcba561eb650fa Reviewed-on: https://go-review.googlesource.com/54710 Reviewed-by: Joe Tsai <thebrokentoaster@gmail.com> Run-TryBot: Joe Tsai <thebrokentoaster@gmail.com>
1 parent d7ec89c commit 392834f

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

src/time/example_test.go

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,76 @@ func ExampleDuration() {
1818
fmt.Printf("The call took %v to run.\n", t1.Sub(t0))
1919
}
2020

21+
func ExampleDuration_Round() {
22+
d, err := time.ParseDuration("1h15m30.918273645s")
23+
if err != nil {
24+
panic(err)
25+
}
26+
27+
round := []time.Duration{
28+
time.Nanosecond,
29+
time.Microsecond,
30+
time.Millisecond,
31+
time.Second,
32+
2 * time.Second,
33+
time.Minute,
34+
10 * time.Minute,
35+
time.Hour,
36+
}
37+
38+
for _, r := range round {
39+
fmt.Printf("d.Round(%6s) = %s\n", r, d.Round(r).String())
40+
}
41+
// Output:
42+
// d.Round( 1ns) = 1h15m30.918273645s
43+
// d.Round( 1µs) = 1h15m30.918274s
44+
// d.Round( 1ms) = 1h15m30.918s
45+
// d.Round( 1s) = 1h15m31s
46+
// d.Round( 2s) = 1h15m30s
47+
// d.Round( 1m0s) = 1h16m0s
48+
// d.Round( 10m0s) = 1h20m0s
49+
// d.Round(1h0m0s) = 1h0m0s
50+
}
51+
52+
func ExampleDuration_String() {
53+
t1 := time.Date(2016, time.August, 15, 0, 0, 0, 0, time.UTC)
54+
t2 := time.Date(2017, time.February, 16, 0, 0, 0, 0, time.UTC)
55+
fmt.Println(t2.Sub(t1).String())
56+
// Output: 4440h0m0s
57+
}
58+
59+
func ExampleDuration_Truncate() {
60+
d, err := time.ParseDuration("1h15m30.918273645s")
61+
if err != nil {
62+
panic(err)
63+
}
64+
65+
trunc := []time.Duration{
66+
time.Nanosecond,
67+
time.Microsecond,
68+
time.Millisecond,
69+
time.Second,
70+
2 * time.Second,
71+
time.Minute,
72+
10 * time.Minute,
73+
time.Hour,
74+
}
75+
76+
for _, t := range trunc {
77+
fmt.Printf("t.Truncate(%6s) = %s\n", t, d.Truncate(t).String())
78+
}
79+
// Output:
80+
// t.Truncate( 1ns) = 1h15m30.918273645s
81+
// t.Truncate( 1µs) = 1h15m30.918273s
82+
// t.Truncate( 1ms) = 1h15m30.918s
83+
// t.Truncate( 1s) = 1h15m30s
84+
// t.Truncate( 2s) = 1h15m30s
85+
// t.Truncate( 1m0s) = 1h15m0s
86+
// t.Truncate( 10m0s) = 1h10m0s
87+
// t.Truncate(1h0m0s) = 1h0m0s
88+
89+
}
90+
2191
var c chan int
2292

2393
func handle(int) {}

0 commit comments

Comments
 (0)