1// Copyright 2019 CUE Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package time
16
17import (
18 "time"
19)
20
21// Common durations. There is no definition for units of Day or larger
22// to avoid confusion across daylight savings time zone transitions.
23//
24// To count the number of units in a Duration, divide:
25//
26// second := time.Second
27// fmt.Print(int64(second/time.Millisecond)) // prints 1000
28//
29// To convert an integer number of units to a Duration, multiply:
30//
31// seconds := 10
32// fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
33const (
34 Nanosecond = 1
35 Microsecond = 1000
36 Millisecond = 1000000
37 Second = 1000000000
38 Minute = 60000000000
39 Hour = 3600000000000
40)
41
42// Duration validates a duration string.
43//
44// Note: this format also accepts strings of the form '1h3m', '2ms', etc.
45// To limit this to seconds only, as often used in JSON, add the !~"hmuµn"
46// constraint.
47func Duration(s string) (bool, error) {
48 if _, err := time.ParseDuration(s); err != nil {
49 return false, err
50 }
51 return true, nil
52}
53
54// FormatDuration converts nanoseconds to a string representing the duration in
55// the form "72h3m0.5s".
56//
57// Leading zero units are omitted. As a special case, durations less than
58// one second use a smaller unit (milli-, micro-, or nanoseconds) to ensure
59// that the leading digit is non-zero. The zero duration formats as 0s.
60func FormatDuration(d int64) string {
61 return time.Duration(d).String()
62}
63
64// ParseDuration reports the nanoseconds represented by a duration string.
65//
66// A duration string is a possibly signed sequence of
67// decimal numbers, each with optional fraction and a unit suffix,
68// such as "300ms", "-1.5h" or "2h45m".
69// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
70func ParseDuration(s string) (int64, error) {
71 d, err := time.ParseDuration(s)
72 if err != nil {
73 return 0, err
74 }
75 return int64(d), nil
76}