Documentation
¶
Overview ¶
Package time provides functionality for measuring and displaying time.
The calendrical calculations always assume a Gregorian calendar, with no leap seconds.
Monotonic Clocks ¶
Operating systems provide both a “wall clock,” which is subject to changes for clock synchronization, and a “monotonic clock,” which is not. The general rule is that the wall clock is for telling time and the monotonic clock is for measuring time. Rather than split the API, in this package the Time returned by time.Now contains both a wall clock reading and a monotonic clock reading; later time-telling operations use the wall clock reading, but later time-measuring operations, specifically comparisons and subtractions, use the monotonic clock reading.
For example, this code always computes a positive elapsed time of approximately 20 milliseconds, even if the wall clock is changed during the operation being timed:
start := time.Now() ... operation that takes 20 milliseconds ... t := time.Now() elapsed := t.Sub(start)
Other idioms, such as time.Since(start), time.Until(deadline), and time.Now().Before(deadline), are similarly robust against wall clock resets.
The rest of this section gives the precise details of how operations use monotonic clocks, but understanding those details is not required to use this package.
The Time returned by time.Now contains a monotonic clock reading. If Time t has a monotonic clock reading, t.Add adds the same duration to both the wall clock and monotonic clock readings to compute the result. Because t.AddDate(y, m, d), t.Round(d), and t.Truncate(d) are wall time computations, they always strip any monotonic clock reading from their results. Because t.In, t.Local, and t.UTC are used for their effect on the interpretation of the wall time, they also strip any monotonic clock reading from their results. The canonical way to strip a monotonic clock reading is to use t = t.Round(0).
If Times t and u both contain monotonic clock readings, the operations t.After(u), t.Before(u), t.Equal(u), t.Compare(u), and t.Sub(u) are carried out using the monotonic clock readings alone, ignoring the wall clock readings. If either t or u contains no monotonic clock reading, these operations fall back to using the wall clock readings.
On some systems the monotonic clock will stop if the computer goes to sleep. On such a system, t.Sub(u) may not accurately reflect the actual time that passed between t and u. The same applies to other functions and methods that subtract times, such as Since, Until, Time.Before, Time.After, Time.Add, Time.Equal and Time.Compare. In some cases, you may need to strip the monotonic clock to get accurate results.
Because the monotonic clock reading has no meaning outside the current process, the serialized forms generated by t.GobEncode, t.MarshalBinary, t.MarshalJSON, and t.MarshalText omit the monotonic clock reading, and t.Format provides no format for it. Similarly, the constructors time.Date, time.Parse, time.ParseInLocation, and time.Unix, as well as the unmarshalers t.GobDecode, t.UnmarshalBinary. t.UnmarshalJSON, and t.UnmarshalText always create times with no monotonic clock reading.
The monotonic clock reading exists only in Time values. It is not a part of Duration values or the Unix times returned by t.Unix and friends.
Note that the Go == operator compares not just the time instant but also the Location and the monotonic clock reading. See the documentation for the Time type for a discussion of equality testing for Time values.
For debugging, the result of t.String does include the monotonic clock reading if present. If t != u because of different monotonic clock readings, that difference will be visible when printing t.String() and u.String().
Timer Resolution ¶
Timer resolution varies depending on the Go runtime, the operating system and the underlying hardware. On Unix, the resolution is ~1ms. On Windows version 1803 and newer, the resolution is ~0.5ms. On older Windows versions, the default resolution is ~16ms, but a higher resolution may be requested using golang.org/x/sys/windows.TimeBeginPeriod.
Index ¶
- Constants
- func After(d Duration) <-chan Time
- func Sleep(d Duration)
- func Tick(d Duration) <-chan Time
- type Duration
- func (d Duration) Abs() Duration
- func (d Duration) Hours() float64
- func (d Duration) Microseconds() int64
- func (d Duration) Milliseconds() int64
- func (d Duration) Minutes() float64
- func (d Duration) Nanoseconds() int64
- func (d Duration) Round(m Duration) Duration
- func (d Duration) Seconds() float64
- func (d Duration) String() string
- func (d Duration) Truncate(m Duration) Duration
- type Location
- type Month
- type ParseError
- type Ticker
- type Time
- func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
- func Now() Time
- func Parse(layout, value string) (Time, error)
- func ParseInLocation(layout, value string, loc *Location) (Time, error)
- func Unix(sec int64, nsec int64) Time
- func UnixMicro(usec int64) Time
- func UnixMilli(msec int64) Time
- func (t Time) Add(d Duration) Time
- func (t Time) AddDate(years int, months int, days int) Time
- func (t Time) After(u Time) bool
- func (t Time) AppendBinary(b []byte) ([]byte, error)
- func (t Time) AppendFormat(b []byte, layout string) []byte
- func (t Time) AppendText(b []byte) ([]byte, error)
- func (t Time) Before(u Time) bool
- func (t Time) Clock() (hour, min, sec int)
- func (t Time) Compare(u Time) int
- func (t Time) Date() (year int, month Month, day int)
- func (t Time) Day() int
- func (t Time) Equal(u Time) bool
- func (t Time) Format(layout string) string
- func (t Time) GoString() string
- func (t *Time) GobDecode(data []byte) error
- func (t Time) GobEncode() ([]byte, error)
- func (t Time) Hour() int
- func (t Time) ISOWeek() (year, week int)
- func (t Time) In(loc *Location) Time
- func (t Time) IsDST() bool
- func (t Time) IsZero() bool
- func (t Time) Local() Time
- func (t Time) Location() *Location
- func (t Time) MarshalBinary() ([]byte, error)
- func (t Time) MarshalJSON() ([]byte, error)
- func (t Time) MarshalText() ([]byte, error)
- func (t Time) Minute() int
- func (t Time) Month() Month
- func (t Time) Nanosecond() int
- func (t Time) Round(d Duration) Time
- func (t Time) Second() int
- func (t Time) String() string
- func (t Time) Sub(u Time) Duration
- func (t Time) Truncate(d Duration) Time
- func (t Time) UTC() Time
- func (t Time) Unix() int64
- func (t Time) UnixMicro() int64
- func (t Time) UnixMilli() int64
- func (t Time) UnixNano() int64
- func (t *Time) UnmarshalBinary(data []byte) error
- func (t *Time) UnmarshalJSON(data []byte) error
- func (t *Time) UnmarshalText(data []byte) error
- func (t Time) Weekday() Weekday
- func (t Time) Year() int
- func (t Time) YearDay() int
- func (t Time) Zone() (name string, offset int)
- func (t Time) ZoneBounds() (start, end Time)
- type Timer
- type Weekday
Examples ¶
- After
- Date
- Duration
- Duration.Abs
- Duration.Hours
- Duration.Microseconds
- Duration.Milliseconds
- Duration.Minutes
- Duration.Nanoseconds
- Duration.Round
- Duration.Seconds
- Duration.String
- Duration.Truncate
- FixedZone
- LoadLocation
- Location
- Month
- NewTicker
- Parse
- ParseDuration
- ParseInLocation
- Since
- Sleep
- Tick
- Time.Add
- Time.AddDate
- Time.After
- Time.AppendBinary
- Time.AppendFormat
- Time.AppendText
- Time.Before
- Time.Date
- Time.Day
- Time.Equal
- Time.Format
- Time.Format (Pad)
- Time.GoString
- Time.Round
- Time.String
- Time.Sub
- Time.Truncate
- Time.Unix
- Unix
- UnixMicro
- UnixMilli
- Until
Constants ¶
const ( Layout = "01/02 03:04:05PM '06 -0700" // The reference time, in numerical order. ANSIC = "Mon Jan _2 15:04:05 2006" UnixDate = "Mon Jan _2 15:04:05 MST 2006" RubyDate = "Mon Jan 02 15:04:05 -0700 2006" RFC822 = "02 Jan 06 15:04 MST" RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone RFC850 = "Monday, 02-Jan-06 15:04:05 MST" RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST" RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone RFC3339 = "2006-01-02T15:04:05Z07:00" RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00" Kitchen = "3:04PM" // Handy time stamps. Stamp = "Jan _2 15:04:05" StampMilli = "Jan _2 15:04:05.000" StampMicro = "Jan _2 15:04:05.000000" StampNano = "Jan _2 15:04:05.000000000" DateTime = "2006-01-02 15:04:05" DateOnly = "2006-01-02" TimeOnly = "15:04:05" )
These are predefined layouts for use in Time.Format and time.Parse. The reference time used in these layouts is the specific time stamp:
01/02 03:04:05PM '06 -0700
(January 2, 15:04:05, 2006, in time zone seven hours west of GMT). That value is recorded as the constant named Layout, listed below. As a Unix time, this is 1136239445. Since MST is GMT-0700, the reference would be printed by the Unix date command as:
Mon Jan 2 15:04:05 MST 2006
It is a regrettable historic error that the date uses the American convention of putting the numerical month before the day.
The example for Time.Format demonstrates the working of the layout string in detail and is a good reference.
Note that the RFC822, RFC850, and RFC1123 formats should be applied only to local times. Applying them to UTC times will use "UTC" as the time zone abbreviation, while strictly speaking those RFCs require the use of "GMT" in that case. When using the RFC1123 or RFC1123Z formats for parsing, note that these formats define a leading zero for the day-in-month portion, which is not strictly allowed by RFC 1123. This will result in an error when parsing date strings that occur in the first 9 days of a given month. In general RFC1123Z should be used instead of RFC1123 for servers that insist on that format, and RFC3339 should be preferred for new protocols. RFC3339, RFC822, RFC822Z, RFC1123, and RFC1123Z are useful for formatting; when used with time.Parse they do not accept all the time formats permitted by the RFCs and they do accept time formats not formally defined. The RFC3339Nano format removes trailing zeros from the seconds field and thus may not sort correctly once formatted.
Most programs can use one of the defined constants as the layout passed to Format or Parse. The rest of this comment can be ignored unless you are creating a custom layout string.
To define your own format, write down what the reference time would look like formatted your way; see the values of constants like ANSIC, StampMicro or Kitchen for examples. The model is to demonstrate what the reference time looks like so that the Format and Parse methods can apply the same transformation to a general time value.
Here is a summary of the components of a layout string. Each element shows by example the formatting of an element of the reference time. Only these values are recognized. Text in the layout string that is not recognized as part of the reference time is echoed verbatim during Format and expected to appear verbatim in the input to Parse.
Year: "2006" "06" Month: "Jan" "January" "01" "1" Day of the week: "Mon" "Monday" Day of the month: "2" "_2" "02" Day of the year: "__2" "002" Hour: "15" "3" "03" (PM or AM) Minute: "4" "04" Second: "5" "05" AM/PM mark: "PM"
Numeric time zone offsets format as follows:
"-0700" ±hhmm "-07:00" ±hh:mm "-07" ±hh "-070000" ±hhmmss "-07:00:00" ±hh:mm:ss
Replacing the sign in the format with a Z triggers the ISO 8601 behavior of printing Z instead of an offset for the UTC zone. Thus:
"Z0700" Z or ±hhmm "Z07:00" Z or ±hh:mm "Z07" Z or ±hh "Z070000" Z or ±hhmmss "Z07:00:00" Z or ±hh:mm:ss
Within the format string, the underscores in "_2" and "__2" represent spaces that may be replaced by digits if the following number has multiple digits, for compatibility with fixed-width Unix time formats. A leading zero represents a zero-padded value.
The formats __2 and 002 are space-padded and zero-padded three-character day of year; there is no unpadded day of year format.
A comma or decimal point followed by one or more zeros represents a fractional second, printed to the given number of decimal places. A comma or decimal point followed by one or more nines represents a fractional second, printed to the given number of decimal places, with trailing zeros removed. For example "15:04:05,000" or "15:04:05.000" formats or parses with millisecond precision.
Some valid layouts are invalid time values for time.Parse, due to formats such as _ for space padding and Z for zone information.
const ( Nanosecond Duration = 1 Microsecond = 1000 * Nanosecond Millisecond = 1000 * Microsecond Second = 1000 * Millisecond Minute = 60 * Second Hour = 60 * Minute )
Common durations. There is no definition for units of Day or larger to avoid confusion across daylight savings time zone transitions.
To count the number of units in a Duration, divide:
second := time.Second fmt.Print(int64(second/time.Millisecond)) // prints 1000
To convert an integer number of units to a Duration, multiply:
seconds := 10 fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
Variables ¶
This section is empty.
Functions ¶
func After ¶
After waits for the duration to elapse and then sends the current time on the returned channel. It is equivalent to NewTimer(d).C.
Before Go 1.23, this documentation warned that the underlying Timer would not be recovered by the garbage collector until the timer fired, and that if efficiency was a concern, code should use NewTimer instead and call Timer.Stop if the timer is no longer needed. As of Go 1.23, the garbage collector can recover unreferenced, unstopped timers. There is no reason to prefer NewTimer when After will do.
Example ¶
package main
import (
"fmt"
"time"
)
var c chan int
func handle(int) {}
func main() {
select {
case m := <-c:
handle(m)
case <-time.After(10 * time.Second):
fmt.Println("timed out")
}
}
Output:
func Sleep ¶
func Sleep(d Duration)
Sleep pauses the current goroutine for at least the duration d. A negative or zero duration causes Sleep to return immediately.
func Tick ¶
Tick is a convenience wrapper for NewTicker providing access to the ticking channel only. Unlike NewTicker, Tick will return nil if d <= 0.
Before Go 1.23, this documentation warned that the underlying Ticker would never be recovered by the garbage collector, and that if efficiency was a concern, code should use NewTicker instead and call Ticker.Stop when the ticker is no longer needed. As of Go 1.23, the garbage collector can recover unreferenced tickers, even if they haven't been stopped. The Stop method is no longer necessary to help the garbage collector. There is no longer any reason to prefer NewTicker when Tick will do.
Example ¶
package main
import (
"fmt"
"time"
)
func statusUpdate() string { return "" }
func main() {
c := time.Tick(5 * time.Second)
for next := range c {
fmt.Printf("%v %s\n", next, statusUpdate())
}
}
Output:
Types ¶
type Duration ¶
type Duration int64
A Duration represents the elapsed time between two instants as an int64 nanosecond count. The representation limits the largest representable duration to approximately 290 years.
Example ¶
package main
import (
"fmt"
"time"
)
func expensiveCall() {}
func main() {
t0 := time.Now()
expensiveCall()
t1 := time.Now()
fmt.Printf("The call took %v to run.\n", t1.Sub(t0))
}
Output:
func ParseDuration ¶
ParseDuration parses a duration string. A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
Example ¶
package main
import (
"fmt"
"time"
)
func main() {
hours, _ := time.ParseDuration("10h")
complex, _ := time.ParseDuration("1h10m10s")
micro, _ := time.ParseDuration("1µs")
// The package also accepts the incorrect but common prefix u for micro.
micro2, _ := time.ParseDuration("1us")
fmt.Println(hours)
fmt.Println(complex)
fmt.Printf("There are %.0f seconds in %v.\n", complex.Seconds(), complex)
fmt.Printf("There are %d nanoseconds in %v.\n", micro.Nanoseconds(), micro)
fmt.Printf("There are %6.2e seconds in %v.\n", micro2.Seconds(), micro2)
}
Output: 10h0m0s 1h10m10s There are 4210 seconds in 1h10m10s. There are 1000 nanoseconds in 1µs. There are 1.00e-06 seconds in 1µs.
func Since ¶
Since returns the time elapsed since t. It is shorthand for time.Now().Sub(t).
Example ¶
package main
import (
"fmt"
"time"
)
func expensiveCall() {}
func main() {
start := time.Now()
expensiveCall()
elapsed := time.Since(start)
fmt.Printf("The call took %v to run.\n", elapsed)
}
Output:
func Until ¶ added in go1.8
Until returns the duration until t. It is shorthand for t.Sub(time.Now()).
Example ¶
package main
import (
"fmt"
"math"
"time"
)
func main() {
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 (Duration) Abs ¶ added in go1.19
Abs returns the absolute value of d. As a special case, Duration(math.MinInt64) is converted to Duration(math.MaxInt64), reducing its magnitude by 1 nanosecond.
Example ¶
package main
import (
"fmt"
"math"
"time"
)
func main() {
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 (Duration) Hours ¶
Hours returns the duration as a floating point number of hours.
Example ¶
package main
import (
"fmt"
"time"
)
func main() {
h, _ := time.ParseDuration("4h30m")
fmt.Printf("I've got %.1f hours of work left.", h.Hours())
}
Output: I've got 4.5 hours of work left.
func (Duration) Microseconds ¶ added in go1.13
Microseconds returns the duration as an integer microsecond count.
Example ¶
package main
import (
"fmt"
"time"
)
func main() {
u, _ := time.ParseDuration("1s")
fmt.Printf("One second is %d microseconds.\n", u.Microseconds())
}
Output: One second is 1000000 microseconds.
func (Duration) Milliseconds ¶ added in go1.13
Milliseconds returns the duration as an integer millisecond count.
Example ¶
package main
import (
"fmt"
"time"
)
func main() {
u, _ := time.ParseDuration("1s")
fmt.Printf("One second is %d milliseconds.\n", u.Milliseconds())
}
Output: One second is 1000 milliseconds.