github.com/solo-io/cue@v0.4.7/pkg/time/duration.go (about)

     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  
    15  package time
    16  
    17  import (
    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  //	second := time.Second
    26  //	fmt.Print(int64(second/time.Millisecond)) // prints 1000
    27  //
    28  // To convert an integer number of units to a Duration, multiply:
    29  //	seconds := 10
    30  //	fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
    31  //
    32  const (
    33  	Nanosecond  = 1
    34  	Microsecond = 1000
    35  	Millisecond = 1000000
    36  	Second      = 1000000000
    37  	Minute      = 60000000000
    38  	Hour        = 3600000000000
    39  )
    40  
    41  // Duration validates a duration string.
    42  //
    43  // Note: this format also accepts strings of the form '1h3m', '2ms', etc.
    44  // To limit this to seconds only, as often used in JSON, add the !~"hmuµn"
    45  // constraint.
    46  func Duration(s string) (bool, error) {
    47  	if _, err := time.ParseDuration(s); err != nil {
    48  		return false, err
    49  	}
    50  	return true, nil
    51  }
    52  
    53  // ParseDuration reports the nanoseconds represented by a duration string.
    54  //
    55  // A duration string is a possibly signed sequence of
    56  // decimal numbers, each with optional fraction and a unit suffix,
    57  // such as "300ms", "-1.5h" or "2h45m".
    58  // Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
    59  func ParseDuration(s string) (int64, error) {
    60  	d, err := time.ParseDuration(s)
    61  	if err != nil {
    62  		return 0, err
    63  	}
    64  	return int64(d), nil
    65  }