1
0
mirror of https://github.com/golang/go synced 2024-11-14 19:50:21 -07:00

time: add examples for Since, Until, Abs and fix some comments

Change-Id: I33b61629dfabffa15065a14fccdb418bab11350d
Reviewed-on: https://go-review.googlesource.com/c/go/+/623915
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: David Chase <drchase@google.com>
This commit is contained in:
cuishuang 2024-10-31 21:45:00 +08:00 committed by Gopher Robot
parent cb163ff60b
commit 08d2403576
4 changed files with 39 additions and 5 deletions

View File

@ -6,6 +6,7 @@ package time_test
import (
"fmt"
"math"
"time"
)
@ -108,6 +109,39 @@ func ExampleParseDuration() {
// There are 1.00e-06 seconds in 1µs.
}
func ExampleSince() {
start := time.Now()
expensiveCall()
elapsed := time.Since(start)
fmt.Printf("The call took %v to run.\n", elapsed)
}
func ExampleUntil() {
futureTime := time.Now().Add(5 * time.Second)
durationUntil := time.Until(futureTime)
fmt.Printf("Duration until future time: %.0f seconds", math.Ceil(durationUntil.Seconds()))
// Output: Duration until future time: 5 seconds
}
func ExampleDuration_Abs() {
positiveDuration := 5 * time.Second
negativeDuration := -3 * time.Second
minInt64CaseDuration := time.Duration(math.MinInt64)
absPositive := positiveDuration.Abs()
absNegative := negativeDuration.Abs()
absSpecial := minInt64CaseDuration.Abs() == time.Duration(math.MaxInt64)
fmt.Printf("Absolute value of positive duration: %v\n", absPositive)
fmt.Printf("Absolute value of negative duration: %v\n", absNegative)
fmt.Printf("Absolute value of MinInt64 equal to MaxInt64: %t\n", absSpecial)
// Output:
// Absolute value of positive duration: 5s
// Absolute value of negative duration: 3s
// Absolute value of MinInt64 equal to MaxInt64: true
}
func ExampleDuration_Hours() {
h, _ := time.ParseDuration("4h30m")
fmt.Printf("I've got %.1f hours of work left.", h.Hours())

View File

@ -1400,7 +1400,7 @@ var defaultLocTests = []struct {
{"Add", func(t1, t2 Time) bool { return t1.Add(Hour).Equal(t2.Add(Hour)) }},
{"Sub", func(t1, t2 Time) bool { return t1.Sub(t2) == t2.Sub(t1) }},
//Original caus for this test case bug 15852
// Original cause for this test case bug 15852
{"AddDate", func(t1, t2 Time) bool { return t1.AddDate(1991, 9, 3) == t2.AddDate(1991, 9, 3) }},
{"UTC", func(t1, t2 Time) bool { return t1.UTC() == t2.UTC() }},