Skip to content

Latest commit

 

History

History
106 lines (79 loc) · 2.59 KB

duration.md

File metadata and controls

106 lines (79 loc) · 2.59 KB

Overview

  1. Using durations & periods
  2. See also datetime doc

Terms

Duration

  1. Represents hours, minutes, seconds, millis, microseconds and nanoseconds
  2. Stored as int64 (nanoseconds between two instants)
  3. Max value is ~290 years
  4. Rust equivalent
  5. JVM equivalent
  6. ISO 8601
  7. Internally stored as nanos

Period

  1. An amount of time meaningful to humans
  2. Generally imprecise because of timezones, daylight savings time, variable month lengths, ...
  3. Measured in Days, Weeks, Months, Years
  4. JVM equivalent
  5. TODO: ISO-8601 parse & format
  6. ISO 8601

Construct (from string)

TODO

Parse (from string)

  1. TODO: ISO 8601
  2. Example
TODO: more here
  1. https://pkg.go.dev/time#ParseDuration

Units:

  • h: hour
  • m: minute
  • s: second
  • ms: millisecond
  • us or µs: microsecond
  • ns: nanosecond

Format (to string)

  1. TODO: ISO 8601
  2. Produces a string which can be Parsed via time.ParseDuration
  3. Example
dur, err := time.ParseDuration("5h4m3s2ms")
...
fmt.Printf("dur: %v", dur.String())
  1. https://pkg.go.dev/time#Duration.String
start := time.Now()

// ... do something ...

elapsed := time.Now().Sub(start)
log.Info().
    Str("elapsed", fmt.Sprintf("%v", elapsed)).
    Msg("total time")
  1. Probably better to wait for channel or a WaitGroup
time.Sleep(100 * time.Millisecond)
time.Sleep(20 * time.Second)
time.Sleep(5 * time.Minute)

Add/Sub

TODO
  1. TODO: more here
  2. Official doc
  1. rounds down (toward zero)
  2. Can truncate to any duration (eg. previous hour, minute, second, ... 5-minutes)
  3. Official doc

Idioms

  1. Avoid time.Since because it hard codes time.Now() (better to inject a time provider)
  2. Avoid time.Until because it hard codes time.Now() (better to inject a time provider)

Other Resources

  1. https://pkg.go.dev/time