time

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 5, 2026 License: BSD-3-Clause Imports: 5 Imported by: 0

Documentation

Overview

Package time provides functionality for measuring and displaying time.

The calendrical calculations always assume a Gregorian calendar, with no leap seconds.

Based on the time package, with fewer features:

  • Time is always stored as UTC internally
  • Fixed time zones (UTC offsets) instead of Locations.
  • Formatting and parsing use C verbs instead of Go verbs.

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 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 Since(start), Until(deadline), and 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 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. 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 constructors Date, Parse, and Unix, 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 == operator compares not just the time instant but also 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().

Index

Constants

View Source
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
View Source
const (
	RFC3339     = "%Y-%m-%dT%H:%M:%S%z"
	RFC3339Nano = "%Y-%m-%dT%H:%M:%S.%f%z"
	DateTime    = "%Y-%m-%d %H:%M:%S"
	DateOnly    = "%Y-%m-%d"
	TimeOnly    = "%H:%M:%S"
)

Commonly used layouts for Format and Parse.

Variables

View Source
var ErrParse = errors.New("time: cannot parse")

ErrParse is returned by Parse when the input cannot be parsed.

Functions

This section is empty.

Types

type CalClock

type CalClock struct {
	Hour   int
	Minute int
	Second int
}

CalClock is a time of day specified by hour, minute, and second.

type CalDate

type CalDate struct {
	Year  int
	Month Month
	Day   int
}

CalDate is a date specified by year, month, and day.

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.

func Since

func Since(t Time) Duration

Since returns the time elapsed since t. It is shorthand for time.Now().Sub(t).

func Until

func Until(t Time) Duration

Until returns the duration until t. It is shorthand for t.Sub(time.Now()).

func (Duration) Abs

func (d Duration) Abs() Duration

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.

func (Duration) Hours

func (d Duration) Hours() float64

Hours returns the duration as a floating point number of hours.

func (Duration) Microseconds

func (d Duration) Microseconds() int64

Microseconds returns the duration as an integer microsecond count.

func (Duration) Milliseconds

func (d Duration) Milliseconds() int64

Milliseconds returns the duration as an integer millisecond count.

func (Duration) Minutes

func (d Duration) Minutes() float64

Minutes returns the duration as a floating point number of minutes.

func (Duration) Nanoseconds

func (d Duration) Nanoseconds() int64

Nanoseconds returns the duration as an integer nanosecond count.

func (Duration) Round

func (d Duration) Round(m Duration) Duration

Round returns the result of rounding d to the nearest multiple of m. The rounding behavior for halfway values is to round away from zero. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, Round returns the maximum (or minimum) duration. If m <= 0, Round returns d unchanged.

func (Duration) Seconds

func (d Duration) Seconds() float64

Seconds returns the duration as a floating point number of seconds.

func (Duration) String

func (d Duration) String(buf []byte) string

String returns a string representing the duration in the form "72h3m0.5s". Leading zero units are omitted. As a special case, durations less than one second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure that the leading digit is non-zero. The zero duration formats as 0s. buf must have a length of at least 25 bytes.

func (Duration) Truncate

func (d Duration) Truncate(m Duration) Duration

Truncate returns the result of rounding d toward zero to a multiple of m. If m <= 0, Truncate returns d unchanged.

type Month

type Month int

A Month specifies a month of the year (January = 1, ...).

const (
	January Month = 1 + iota
	February
	March
	April
	May
	June
	July
	August
	September
	October
	November
	December
)

type Offset

type Offset int

Offset represents a fixed offset from UTC in seconds east of UTC.

const UTC Offset = 0

UTC represents Universal Coordinated Time (UTC).

type Time

type Time struct {
	// contains filtered or unexported fields
}

A Time represents an instant in time with nanosecond precision. Time always represents UTC internally.

Programs using times should typically store and pass them as values, not pointers. That is, time variables and struct fields should be of type time.Time, not *time.Time.

The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC. As this time is unlikely to come up in practice, the Time.IsZero method gives a simple way of detecting a time that has not been initialized explicitly.

In addition to the required "wall clock" reading, a Time may contain an optional reading of the current process's monotonic clock, to provide additional precision for comparison or subtraction. See the "Monotonic Clocks" section in the package documentation for details.

func Date

func Date(year int, month Month, day, hour, min, sec, nsec int, offset Offset) Time

Date returns the Time in UTC corresponding to

yyyy-mm-dd hh:mm:ss + nsec nanoseconds

with respect to the given offset (seconds east of UTC).

The month, day, hour, min, sec, and nsec values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 1.

A daylight savings time transition skips or repeats times. For example, in the United States, March 13, 2011 2:15am never occurred, while November 6, 2011 1:15am occurred twice. In such cases, the choice of time zone, and therefore the time, is not well-defined. Date returns a time that is correct in one of the two zones involved in the transition, but it does not guarantee which.

func Now

func Now() Time

Now returns the current time in UTC.

func Parse

func Parse(layout string, value string, offset Offset) (Time, error)

Parse parses value per layout (strptime verbs) and returns the Time. offset specifies what timezone the input value is in.

func Unix

func Unix(sec int64, nsec int64) Time

Unix returns the local Time corresponding to the given Unix time, sec seconds and nsec nanoseconds since January 1, 1970 UTC. It is valid to pass nsec outside the range [0, 999999999]. Not all sec values have a corresponding time value. One such value is 1<<63-1 (the largest int64 value).

func UnixMicro

func UnixMicro(usec int64) Time

UnixMicro returns the local Time corresponding to the given Unix time, usec microseconds since January 1, 1970 UTC.

func UnixMilli

func UnixMilli(msec int64) Time

UnixMilli returns the local Time corresponding to the given Unix time, msec milliseconds since January 1, 1970 UTC.

func (Time) Add

func (t Time) Add(d Duration) Time

Add returns the time t+d.

func (Time) AddDate

func (t Time) AddDate(years int, months int, days int) Time

AddDate returns the time corresponding to adding the given number of years, months, and days to t. For example, AddDate(-1, 2, 3) applied to January 1, 2011 returns March 4, 2010.

AddDate normalizes its result in the same way that Date does, so, for example, adding one month to October 31 yields December 1, the normalized form for November 31.

func (Time) After

func (t Time) After(u Time) bool

After reports whether the time instant t is after u.

func (Time) Before

func (t Time) Before(u Time) bool

Before reports whether the time instant t is before u.

func (Time) Clock

func (t Time) Clock(offset Offset) CalClock

Clock returns the hour, minute, and second within the day specified by t, adjusted by the given offset (seconds east of UTC).

func (Time) Compare

func (t Time) Compare(u Time) int

Compare compares the time instant t with u. If t is before u, it returns -1; if t is after u, it returns +1; if they're the same, it returns 0.

func (Time) Date

func (t Time) Date(offset Offset) CalDate

Date returns the year, month, and day in which t occurs, adjusted by the given offset (seconds east of UTC).

func (Time) Day

func (t Time) Day() int

Day returns the day of the month specified by t.

func (Time) Equal

func (t Time) Equal(u Time) bool

Equal reports whether t and u represent the same time instant. Unlike the == operator, Equal ignores monotonic clock readings.

func (Time) Format

func (t Time) Format(buf []byte, layout string, offset Offset) string

Format formats the time per layout (strftime verbs like "%Y-%m-%d"), writing into buf. Returns the formatted string (a view into buf). buf length must be large enough for the formatted output plus a null terminator.

func (Time) Hour

func (t Time) Hour() int

Hour returns the hour within the day specified by t, in the range [0, 23].

func (Time) ISOWeek

func (t Time) ISOWeek() (int, int)

ISOWeek returns the ISO 8601 year and week number in which t occurs. Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 of year n+1.

func (Time) IsZero

func (t Time) IsZero() bool

IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.

func (Time) Minute

func (t Time) Minute() int

Minute returns the minute offset within the hour specified by t, in the range [0, 59].

func (Time) Month

func (t Time) Month() Month

Month returns the month of the year specified by t.

func (Time) Nanosecond

func (t Time) Nanosecond() int

Nanosecond returns the nanosecond offset within the second specified by t, in the range [0, 999999999].

func (Time) Round

func (t Time) Round(d Duration) Time

Round returns the result of rounding t to the nearest multiple of d (since the zero time). The rounding behavior for halfway values is to round up. If d <= 0, Round returns t stripped of any monotonic clock reading but otherwise unchanged.

Round operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time.

func (Time) Second

func (t Time) Second() int

Second returns the second offset within the minute specified by t, in the range [0, 59].

func (Time) String

func (t Time) String(buf []byte) string

String formats the time as ISO 8601 "2006-01-02T15:04:05Z", writing into buf. Returns the formatted string (a view into buf). buf must have a length of at least 21 bytes.

func (Time) Sub

func (t Time) Sub(u Time) Duration

Sub returns the duration t-u. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, the maximum (or minimum) duration will be returned. To compute t-d for a duration d, use t.Add(-d).

func (Time) Truncate

func (t Time) Truncate(d Duration) Time

Truncate returns the result of rounding t down to a multiple of d (since the zero time). If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged.

Truncate operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time.

func (Time) Unix

func (t Time) Unix() int64

Unix returns t as a Unix time, the number of seconds elapsed since January 1, 1970 UTC.

Unix-like operating systems often record time as a 32-bit count of seconds, but since the method here returns a 64-bit value it is valid for billions of years into the past or future.

func (Time) UnixMicro

func (t Time) UnixMicro() int64

UnixMicro returns t as a Unix time, the number of microseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in microseconds cannot be represented by an int64 (a date before year -290307 or after year 294246).

func (Time) UnixMilli

func (t Time) UnixMilli() int64

UnixMilli returns t as a Unix time, the number of milliseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in milliseconds cannot be represented by an int64 (a date more than 292 million years before or after 1970).

func (Time) UnixNano

func (t Time) UnixNano() int64

UnixNano returns t as a Unix time, the number of nanoseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in nanoseconds cannot be represented by an int64 (a date before the year 1678 or after 2262). Note that this means the result of calling UnixNano on the zero Time is undefined.

func (Time) Weekday

func (t Time) Weekday() Weekday

Weekday returns the day of the week specified by t.

func (Time) Year

func (t Time) Year() int

Year returns the year in which t occurs.

func (Time) YearDay

func (t Time) YearDay() int

YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years, and [1,366] in leap years.

type TimeResult

type TimeResult struct {
	// contains filtered or unexported fields
}

TimeResult is a helper struct for returning a Time and an error from a function.

type Weekday

type Weekday int

A Weekday specifies a day of the week (Sunday = 0, ...).

const (
	Sunday Weekday = iota
	Monday
	Tuesday
	Wednesday
	Thursday
	Friday
	Saturday
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL