version: 1.10

package time

import "time"

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:

  1. start := time.Now()
  2. ... operation that takes 20 milliseconds ...
  3. t := time.Now()
  4. 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), 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.

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.

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().

Index

Examples

Package files

format.go sleep.go sys_unix.go tick.go time.go zoneinfo.go zoneinfo_read.go zoneinfo_unix.go

Constants

  1. const (
  2. ANSIC = "Mon Jan _2 15:04:05 2006"
  3. UnixDate = "Mon Jan _2 15:04:05 MST 2006"
  4. RubyDate = "Mon Jan 02 15:04:05 -0700 2006"
  5. RFC822 = "02 Jan 06 15:04 MST"
  6. RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
  7. RFC850 = "Monday, 02-Jan-06 15:04:05 MST"
  8. RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST"
  9. RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
  10. RFC3339 = "2006-01-02T15:04:05Z07:00"
  11. RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
  12. Kitchen = "3:04PM"
  13. // Handy time stamps.
  14. Stamp = "Jan _2 15:04:05"
  15. StampMilli = "Jan _2 15:04:05.000"
  16. StampMicro = "Jan _2 15:04:05.000000"
  17. StampNano = "Jan _2 15:04:05.000000000"
  18. )

These are predefined layouts for use in Time.Format and time.Parse. The
reference time used in the layouts is the specific time:

  1. Mon Jan 2 15:04:05 MST 2006

which is Unix time 1136239445. Since MST is GMT-0700, the reference time can be
thought of as

  1. 01/02 03:04:05PM '06 -0700

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.

Some valid layouts are invalid time values for time.Parse, due to formats such
as _ for space padding and Z for zone information.

Within the format string, an underscore _ represents a space that may be
replaced by a digit if the following number (a day) has two digits; for
compatibility with fixed-width Unix time formats.

A decimal point followed by one or more zeros represents a fractional second,
printed to the given number of decimal places. A decimal point followed by one
or more nines represents a fractional second, printed to the given number of
decimal places, with trailing zeros removed. When parsing (only), the input may
contain a fractional second field immediately after the seconds field, even if
the layout does not signify its presence. In that case a decimal point followed
by a maximal series of digits is parsed as a fractional second.

Numeric time zone offsets format as follows:

  1. -0700 ±hhmm
  2. -07:00 ±hh:mm
  3. -07 ±hh

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:

  1. Z0700 Z or ±hhmm
  2. Z07:00 Z or ±hh:mm
  3. Z07 Z or ±hh

The recognized day of week formats are “Mon” and “Monday”. The recognized month
formats are “Jan” and “January”.

Text in the format 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.

The executable 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. 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. The RFC3339Nano format removes trailing zeros from the seconds field and
thus may not sort correctly once formatted.

func After

  1. func After(d Duration) <-chan Time

After waits for the duration to elapse and then sends the current time on the
returned channel. It is equivalent to NewTimer(d).C. The underlying Timer is not
recovered by the garbage collector until the timer fires. If efficiency is a
concern, use NewTimer instead and call Timer.Stop if the timer is no longer
needed.


Example:

  1. select {
  2. case m := <-c:
  3. handle(m)
  4. case <-time.After(5 * time.Minute):
  5. fmt.Println("timed out")
  6. }

func Sleep

  1. 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.


Example:

  1. time.Sleep(100 * time.Millisecond)

func Tick

  1. func Tick(d Duration) <-chan Time

Tick is a convenience wrapper for NewTicker providing access to the ticking
channel only. While Tick is useful for clients that have no need to shut down
the Ticker, be aware that without a way to shut it down the underlying Ticker
cannot be recovered by the garbage collector; it “leaks”. Unlike NewTicker, Tick
will return nil if d <= 0.


Example:

  1. c := time.Tick(1 * time.Minute)
  2. for now := range c {
  3. fmt.Printf("%v %s\n", now, statusUpdate())
  4. }

type Duration

  1. 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.

  1. const (
  2. Nanosecond Duration = 1
  3. Microsecond = 1000 * Nanosecond
  4. Millisecond = 1000 * Microsecond
  5. Second = 1000 * Millisecond
  6. Minute = 60 * Second
  7. Hour = 60 * Minute
  8. )

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:

  1. second := time.Second
  2. fmt.Print(int64(second/time.Millisecond)) // prints 1000

To convert an integer number of units to a Duration, multiply:

  1. seconds := 10
  2. fmt.Print(time.Duration(seconds)*time.Second) // prints 10s


Example:

  1. t0 := time.Now()
  2. expensiveCall()
  3. t1 := time.Now()
  4. fmt.Printf("The call took %v to run.\n", t1.Sub(t0))

func ParseDuration

  1. func ParseDuration(s string) (Duration, error)

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:

  1. hours, _ := time.ParseDuration("10h")
  2. complex, _ := time.ParseDuration("1h10m10s")
  3. fmt.Println(hours)
  4. fmt.Println(complex)
  5. fmt.Printf("there are %.0f seconds in %v\n", complex.Seconds(), complex)
  6. // Output:
  7. // 10h0m0s
  8. // 1h10m10s
  9. // there are 4210 seconds in 1h10m10s

func Since

  1. func Since(t Time) Duration

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

func Until

  1. func Until(t Time) Duration

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

func (Duration) Hours

  1. func (d Duration) Hours() float64

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


Example:

  1. h, _ := time.ParseDuration("4h30m")
  2. fmt.Printf("I've got %.1f hours of work left.", h.Hours())
  3. // Output: I've got 4.5 hours of work left.

func (Duration) Minutes

  1. func (d Duration) Minutes() float64

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


Example:

  1. m, _ := time.ParseDuration("1h30m")
  2. fmt.Printf("The movie is %.0f minutes long.", m.Minutes())
  3. // Output: The movie is 90 minutes long.

func (Duration) Nanoseconds

  1. func (d Duration) Nanoseconds() int64

Nanoseconds returns the duration as an integer nanosecond count.


Example:

  1. ns, _ := time.ParseDuration("1000ns")
  2. fmt.Printf("one microsecond has %d nanoseconds.", ns.Nanoseconds())
  3. // Output: one microsecond has 1000 nanoseconds.

func (Duration) Round

  1. 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.


Example:

  1. d, err := time.ParseDuration("1h15m30.918273645s")
  2. if err != nil {
  3. panic(err)
  4. }
  5. round := []time.Duration{
  6. time.Nanosecond,
  7. time.Microsecond,
  8. time.Millisecond,
  9. time.Second,
  10. 2 * time.Second,
  11. time.Minute,
  12. 10 * time.Minute,
  13. time.Hour,
  14. }
  15. for _, r := range round {
  16. fmt.Printf("d.Round(%6s) = %s\n", r, d.Round(r).String())
  17. }
  18. // Output:
  19. // d.Round( 1ns) = 1h15m30.918273645s
  20. // d.Round( 1µs) = 1h15m30.918274s
  21. // d.Round( 1ms) = 1h15m30.918s
  22. // d.Round( 1s) = 1h15m31s
  23. // d.Round( 2s) = 1h15m30s
  24. // d.Round( 1m0s) = 1h16m0s
  25. // d.Round( 10m0s) = 1h20m0s
  26. // d.Round(1h0m0s) = 1h0m0s

func (Duration) Seconds

  1. func (d Duration) Seconds() float64

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


Example:

  1. m, _ := time.ParseDuration("1m30s")
  2. fmt.Printf("take off in t-%.0f seconds.", m.Seconds())
  3. // Output: take off in t-90 seconds.

func (Duration) String

  1. func (d Duration) String() 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.


Example:

  1. t1 := time.Date(2016, time.August, 15, 0, 0, 0, 0, time.UTC)
  2. t2 := time.Date(2017, time.February, 16, 0, 0, 0, 0, time.UTC)
  3. fmt.Println(t2.Sub(t1).String())
  4. // Output: 4440h0m0s

func (Duration) Truncate

  1. 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.


Example:

  1. d, err := time.ParseDuration("1h15m30.918273645s")
  2. if err != nil {
  3. panic(err)
  4. }
  5. trunc := []time.Duration{
  6. time.Nanosecond,
  7. time.Microsecond,
  8. time.Millisecond,
  9. time.Second,
  10. 2 * time.Second,
  11. time.Minute,
  12. 10 * time.Minute,
  13. time.Hour,
  14. }
  15. for _, t := range trunc {
  16. fmt.Printf("t.Truncate(%6s) = %s\n", t, d.Truncate(t).String())
  17. }
  18. // Output:
  19. // t.Truncate( 1ns) = 1h15m30.918273645s
  20. // t.Truncate( 1µs) = 1h15m30.918273s
  21. // t.Truncate( 1ms) = 1h15m30.918s
  22. // t.Truncate( 1s) = 1h15m30s
  23. // t.Truncate( 2s) = 1h15m30s
  24. // t.Truncate( 1m0s) = 1h15m0s
  25. // t.Truncate( 10m0s) = 1h10m0s
  26. // t.Truncate(1h0m0s) = 1h0m0s

type Location

  1. type Location struct {
  2. // contains filtered or unexported fields
  3. }

A Location maps time instants to the zone in use at that time. Typically, the
Location represents the collection of time offsets in use in a geographical
area, such as CEST and CET for central Europe.

  1. var Local *Location = &localLoc

Local represents the system’s local time zone.

  1. var UTC *Location = &utcLoc

UTC represents Universal Coordinated Time (UTC).


Example:

  1. // China doesn't have daylight saving. It uses a fixed 8 hour offset from UTC.
  2. secondsEastOfUTC := int((8 * time.Hour).Seconds())
  3. beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)
  4. // If the system has a timezone database present, it's possible to load a location
  5. // from that, e.g.:
  6. // newYork, err := time.LoadLocation("America/New_York")
  7. // Creating a time requires a location. Common locations are time.Local and time.UTC.
  8. timeInUTC := time.Date(2009, 1, 1, 12, 0, 0, 0, time.UTC)
  9. sameTimeInBeijing := time.Date(2009, 1, 1, 20, 0, 0, 0, beijing)
  10. // Although the UTC clock time is 1200 and the Beijing clock time is 2000, Beijing is
  11. // 8 hours ahead so the two dates actually represent the same instant.
  12. timesAreEqual := timeInUTC.Equal(sameTimeInBeijing)
  13. fmt.Println(timesAreEqual)
  14. // Output:
  15. // true

func FixedZone

  1. func FixedZone(name string, offset int) *Location

FixedZone returns a Location that always uses the given zone name and offset
(seconds east of UTC).

func LoadLocation

  1. func LoadLocation(name string) (*Location, error)

LoadLocation returns the Location with the given name.

If the name is “” or “UTC”, LoadLocation returns UTC. If the name is “Local”,
LoadLocation returns Local.

Otherwise, the name is taken to be a location name corresponding to a file in
the IANA Time Zone database, such as “America/New_York”.

The time zone database needed by LoadLocation may not be present on all systems,
especially non-Unix systems. LoadLocation looks in the directory or uncompressed
zip file named by the ZONEINFO environment variable, if any, then looks in known
installation locations on Unix systems, and finally looks in
$GOROOT/lib/time/zoneinfo.zip.

func LoadLocationFromTZData

  1. func LoadLocationFromTZData(name string, data []byte) (*Location, error)

LoadLocationFromTZData returns a Location with the given name initialized from
the IANA Time Zone database-formatted data. The data should be in the format of
a standard IANA time zone file (for example, the content of /etc/localtime on
Unix systems).

func (*Location) String

  1. func (l *Location) String() string

String returns a descriptive name for the time zone information, corresponding
to the name argument to LoadLocation or FixedZone.

type Month

  1. type Month int

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

  1. const (
  2. January Month = 1 + iota
  3. February
  4. March
  5. April
  6. May
  7. June
  8. July
  9. August
  10. September
  11. October
  12. November
  13. December
  14. )


Example:

  1. _, month, day := time.Now().Date()
  2. if month == time.November && day == 10 {
  3. fmt.Println("Happy Go day!")
  4. }

func (Month) String

  1. func (m Month) String() string

String returns the English name of the month (“January”, “February”, …).

type ParseError

  1. type ParseError struct {
  2. Layout string
  3. Value string
  4. LayoutElem string
  5. ValueElem string
  6. Message string
  7. }

ParseError describes a problem parsing a time string.

func (*ParseError) Error

  1. func (e *ParseError) Error() string

Error returns the string representation of a ParseError.

type Ticker

  1. type Ticker struct {
  2. C <-chan Time // The channel on which the ticks are delivered.
  3. // contains filtered or unexported fields
  4. }

A Ticker holds a channel that delivers `ticks’ of a clock at intervals.

func NewTicker

  1. func NewTicker(d Duration) *Ticker

NewTicker returns a new Ticker containing a channel that will send the time with
a period specified by the duration argument. It adjusts the intervals or drops
ticks to make up for slow receivers. The duration d must be greater than zero;
if not, NewTicker will panic. Stop the ticker to release associated resources.


Example:

  1. ticker := time.NewTicker(time.Second)
  2. defer ticker.Stop()
  3. done := make(chan bool)
  4. go func() {
  5. time.Sleep(10 * time.Second)
  6. done <- true
  7. }()
  8. for {
  9. select {
  10. case <-done:
  11. fmt.Println("Done!")
  12. return
  13. case t := <-ticker.C:
  14. fmt.Println("Current time: ", t)
  15. }
  16. }

func (*Ticker) Stop

  1. func (t *Ticker) Stop()

Stop turns off a ticker. After Stop, no more ticks will be sent. Stop does not
close the channel, to prevent a read from the channel succeeding incorrectly.

type Time

  1. type Time struct {
  2. // contains filtered or unexported fields
  3. }

A Time represents an instant in time with nanosecond precision.

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.

A Time value can be used by multiple goroutines simultaneously except that the
methods GobDecode, UnmarshalBinary, UnmarshalJSON and UnmarshalText are not
concurrency-safe.

Time instants can be compared using the Before, After, and Equal methods. The
Sub method subtracts two instants, producing a Duration. The Add method adds a
Time and a Duration, producing a 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 IsZero method gives a simple
way of detecting a time that has not been initialized explicitly.

Each Time has associated with it a Location, consulted when computing the
presentation form of the time, such as in the Format, Hour, and Year methods.
The methods Local, UTC, and In return a Time with a specific location. Changing
the location in this way changes only the presentation; it does not change the
instant in time being denoted and therefore does not affect the computations
described in earlier paragraphs.

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.

Note that the Go == operator compares not just the time instant but also the
Location and the monotonic clock reading. Therefore, Time values should not be
used as map or database keys without first guaranteeing that the identical
Location has been set for all values, which can be achieved through use of the
UTC or Local method, and that the monotonic clock reading has been stripped by
setting t = t.Round(0). In general, prefer t.Equal(u) to t == u, since t.Equal
uses the most accurate comparison available and correctly handles the case when
only one of its arguments has a monotonic clock reading.

func Date

  1. func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time

Date returns the Time corresponding to

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

in the appropriate zone for that time in the given location.

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.

Date panics if loc is nil.


Example:

  1. t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
  2. fmt.Printf("Go launched at %s\n", t.Local())
  3. // Output: Go launched at 2009-11-10 15:00:00 -0800 PST

func Now

  1. func Now() Time

Now returns the current local time.

func Parse

  1. func Parse(layout, value string) (Time, error)

Parse parses a formatted string and returns the time value it represents. The
layout defines the format by showing how the reference time, defined to be

  1. Mon Jan 2 15:04:05 -0700 MST 2006

would be interpreted if it were the value; it serves as an example of the input
format. The same interpretation will then be made to the input string.

Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard and
convenient representations of the reference time. For more information about the
formats and the definition of the reference time, see the documentation for
ANSIC and the other constants defined by this package. Also, the executable
example for Time.Format demonstrates the working of the layout string in detail
and is a good reference.

Elements omitted from the value are assumed to be zero or, when zero is
impossible, one, so parsing “3:04pm” returns the time corresponding to Jan 1,
year 0, 15:04:00 UTC (note that because the year is 0, this time is before the
zero Time). Years must be in the range 0000..9999. The day of the week is
checked for syntax but it is otherwise ignored.

In the absence of a time zone indicator, Parse returns a time in UTC.

When parsing a time with a zone offset like -0700, if the offset corresponds to
a time zone used by the current location (Local), then Parse uses that location
and zone in the returned time. Otherwise it records the time as being in a
fabricated location with time fixed at the given zone offset.

When parsing a time with a zone abbreviation like MST, if the zone abbreviation
has a defined offset in the current location, then that offset is used. The zone
abbreviation “UTC” is recognized as UTC regardless of location. If the zone
abbreviation is unknown, Parse records the time as being in a fabricated
location with the given zone abbreviation and a zero offset. This choice means
that such a time can be parsed and reformatted with the same layout losslessly,
but the exact instant used in the representation will differ by the actual zone
offset. To avoid such problems, prefer time layouts that use a numeric zone
offset, or use ParseInLocation.


Example:

  1. // See the example for Time.Format for a thorough description of how
  2. // to define the layout string to parse a time.Time value; Parse and
  3. // Format use the same model to describe their input and output.
  4. // longForm shows by example how the reference time would be represented in
  5. // the desired layout.
  6. const longForm = "Jan 2, 2006 at 3:04pm (MST)"
  7. t, _ := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)")
  8. fmt.Println(t)
  9. // shortForm is another way the reference time would be represented
  10. // in the desired layout; it has no time zone present.
  11. // Note: without explicit zone, returns time in UTC.
  12. const shortForm = "2006-Jan-02"
  13. t, _ = time.Parse(shortForm, "2013-Feb-03")
  14. fmt.Println(t)
  15. // Some valid layouts are invalid time values, due to format specifiers
  16. // such as _ for space padding and Z for zone information.
  17. // For example the RFC3339 layout 2006-01-02T15:04:05Z07:00
  18. // contains both Z and a time zone offset in order to handle both valid options:
  19. // 2006-01-02T15:04:05Z
  20. // 2006-01-02T15:04:05+07:00
  21. t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")
  22. fmt.Println(t)
  23. t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05+07:00")
  24. fmt.Println(t)
  25. _, err := time.Parse(time.RFC3339, time.RFC3339)
  26. fmt.Println("error", err) // Returns an error as the layout is not a valid time value
  27. // Output:
  28. // 2013-02-03 19:54:00 -0800 PST
  29. // 2013-02-03 00:00:00 +0000 UTC
  30. // 2006-01-02 15:04:05 +0000 UTC
  31. // 2006-01-02 15:04:05 +0700 +0700
  32. // error parsing time "2006-01-02T15:04:05Z07:00": extra text: 07:00

func ParseInLocation

  1. func ParseInLocation(layout, value string, loc *Location) (Time, error)

ParseInLocation is like Parse but differs in two important ways. First, in the
absence of time zone information, Parse interprets a time as UTC;
ParseInLocation interprets the time as in the given location. Second, when given
a zone offset or abbreviation, Parse tries to match it against the Local
location; ParseInLocation uses the given location.


Example:

  1. loc, _ := time.LoadLocation("Europe/Berlin")
  2. const longForm = "Jan 2, 2006 at 3:04pm (MST)"
  3. t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)
  4. fmt.Println(t)
  5. // Note: without explicit zone, returns time in given location.
  6. const shortForm = "2006-Jan-02"
  7. t, _ = time.ParseInLocation(shortForm, "2012-Jul-09", loc)
  8. fmt.Println(t)
  9. // Output:
  10. // 2012-07-09 05:02:00 +0200 CEST
  11. // 2012-07-09 00:00:00 +0200 CEST

func Unix

  1. 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 (Time) Add

  1. func (t Time) Add(d Duration) Time

Add returns the time t+d.


Example:

  1. start := time.Date(2009, 1, 1, 12, 0, 0, 0, time.UTC)
  2. afterTenSeconds := start.Add(time.Second * 10)
  3. afterTenMinutes := start.Add(time.Minute * 10)
  4. afterTenHours := start.Add(time.Hour * 10)
  5. afterTenDays := start.Add(time.Hour * 24 * 10)
  6. fmt.Printf("start = %v\n", start)
  7. fmt.Printf("start.Add(time.Second * 10) = %v\n", afterTenSeconds)
  8. fmt.Printf("start.Add(time.Minute * 10) = %v\n", afterTenMinutes)
  9. fmt.Printf("start.Add(time.Hour * 10) = %v\n", afterTenHours)
  10. fmt.Printf("start.Add(time.Hour * 24 * 10) = %v\n", afterTenDays)
  11. // Output:
  12. // start = 2009-01-01 12:00:00 +0000 UTC
  13. // start.Add(time.Second * 10) = 2009-01-01 12:00:10 +0000 UTC
  14. // start.Add(time.Minute * 10) = 2009-01-01 12:10:00 +0000 UTC
  15. // start.Add(time.Hour * 10) = 2009-01-01 22:00:00 +0000 UTC
  16. // start.Add(time.Hour * 24 * 10) = 2009-01-11 12:00:00 +0000 UTC

func (Time) AddDate

  1. 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.


Example:

  1. start := time.Date(2009, 1, 1, 0, 0, 0, 0, time.UTC)
  2. oneDayLater := start.AddDate(0, 0, 1)
  3. oneMonthLater := start.AddDate(0, 1, 0)
  4. oneYearLater := start.AddDate(1, 0, 0)
  5. fmt.Printf("oneDayLater: start.AddDate(0, 0, 1) = %v\n", oneDayLater)
  6. fmt.Printf("oneMonthLater: start.AddDate(0, 1, 0) = %v\n", oneMonthLater)
  7. fmt.Printf("oneYearLater: start.AddDate(1, 0, 0) = %v\n", oneYearLater)
  8. // Output:
  9. // oneDayLater: start.AddDate(0, 0, 1) = 2009-01-02 00:00:00 +0000 UTC
  10. // oneMonthLater: start.AddDate(0, 1, 0) = 2009-02-01 00:00:00 +0000 UTC
  11. // oneYearLater: start.AddDate(1, 0, 0) = 2010-01-01 00:00:00 +0000 UTC

func (Time) After

  1. func (t Time) After(u Time) bool

After reports whether the time instant t is after u.


Example:

  1. year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
  2. year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)
  3. isYear3000AfterYear2000 := year3000.After(year2000) // True
  4. isYear2000AfterYear3000 := year2000.After(year3000) // False
  5. fmt.Printf("year3000.After(year2000) = %v\n", isYear3000AfterYear2000)
  6. fmt.Printf("year2000.After(year3000) = %v\n", isYear2000AfterYear3000)
  7. // Output:
  8. // year3000.After(year2000) = true
  9. // year2000.After(year3000) = false

func (Time) AppendFormat

  1. func (t Time) AppendFormat(b []byte, layout string) []byte

AppendFormat is like Format but appends the textual representation to b and
returns the extended buffer.


Example:

  1. t := time.Date(2017, time.November, 4, 11, 0, 0, 0, time.UTC)
  2. text := []byte("Time: ")
  3. text = t.AppendFormat(text, time.Kitchen)
  4. fmt.Println(string(text))
  5. // Output:
  6. // Time: 11:00AM

func (Time) Before

  1. func (t Time) Before(u Time) bool

Before reports whether the time instant t is before u.


Example:

  1. year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
  2. year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)
  3. isYear2000BeforeYear3000 := year2000.Before(year3000) // True
  4. isYear3000BeforeYear2000 := year3000.Before(year2000) // False
  5. fmt.Printf("year2000.Before(year3000) = %v\n", isYear2000BeforeYear3000)
  6. fmt.Printf("year3000.Before(year2000) = %v\n", isYear3000BeforeYear2000)
  7. // Output:
  8. // year2000.Before(year3000) = true
  9. // year3000.Before(year2000) = false

func (Time) Clock

  1. func (t Time) Clock() (hour, min, sec int)

Clock returns the hour, minute, and second within the day specified by t.

func (Time) Date

  1. func (t Time) Date() (year int, month Month, day int)

Date returns the year, month, and day in which t occurs.


Example:

  1. d := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
  2. year, month, day := d.Date()
  3. fmt.Printf("year = %v\n", year)
  4. fmt.Printf("month = %v\n", month)
  5. fmt.Printf("day = %v\n", day)
  6. // Output:
  7. // year = 2000
  8. // month = February
  9. // day = 1

func (Time) Day

  1. func (t Time) Day() int

Day returns the day of the month specified by t.


Example:

  1. d := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
  2. day := d.Day()
  3. fmt.Printf("day = %v\n", day)
  4. // Output:
  5. // day = 1

func (Time) Equal

  1. func (t Time) Equal(u Time) bool

Equal reports whether t and u represent the same time instant. Two times can be
equal even if they are in different locations. For example, 6:00 +0200 CEST and
4:00 UTC are Equal. See the documentation on the Time type for the pitfalls of
using == with Time values; most code should use Equal instead.


Example:

  1. secondsEastOfUTC := int((8 * time.Hour).Seconds())
  2. beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)
  3. // Unlike the equal operator, Equal is aware that d1 and d2 are the
  4. // same instant but in different time zones.
  5. d1 := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
  6. d2 := time.Date(2000, 2, 1, 20, 30, 0, 0, beijing)
  7. datesEqualUsingEqualOperator := d1 == d2
  8. datesEqualUsingFunction := d1.Equal(d2)
  9. fmt.Printf("datesEqualUsingEqualOperator = %v\n", datesEqualUsingEqualOperator)
  10. fmt.Printf("datesEqualUsingFunction = %v\n", datesEqualUsingFunction)
  11. // Output:
  12. // datesEqualUsingEqualOperator = false
  13. // datesEqualUsingFunction = true

func (Time) Format

  1. func (t Time) Format(layout string) string

Format returns a textual representation of the time value formatted according to
layout, which defines the format by showing how the reference time, defined to
be

  1. Mon Jan 2 15:04:05 -0700 MST 2006

would be displayed if it were the value; it serves as an example of the desired
output. The same display rules will then be applied to the time value.

A fractional second is represented by adding a period and zeros to the end of
the seconds section of layout string, as in “15:04:05.000” to format a time
stamp with millisecond precision.

Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard and
convenient representations of the reference time. For more information about the
formats and the definition of the reference time, see the documentation for
ANSIC and the other constants defined by this package.


Example:

  1. // Parse a time value from a string in the standard Unix format.
  2. t, err := time.Parse(time.UnixDate, "Sat Mar 7 11:06:39 PST 2015")
  3. if err != nil { // Always check errors even if they should not happen.
  4. panic(err)
  5. }
  6. // time.Time's Stringer method is useful without any format.
  7. fmt.Println("default format:", t)
  8. // Predefined constants in the package implement common layouts.
  9. fmt.Println("Unix format:", t.Format(time.UnixDate))
  10. // The time zone attached to the time value affects its output.
  11. fmt.Println("Same, in UTC:", t.UTC().Format(time.UnixDate))
  12. // The rest of this function demonstrates the properties of the
  13. // layout string used in the format.
  14. // The layout string used by the Parse function and Format method
  15. // shows by example how the reference time should be represented.
  16. // We stress that one must show how the reference time is formatted,
  17. // not a time of the user's choosing. Thus each layout string is a
  18. // representation of the time stamp,
  19. // Jan 2 15:04:05 2006 MST
  20. // An easy way to remember this value is that it holds, when presented
  21. // in this order, the values (lined up with the elements above):
  22. // 1 2 3 4 5 6 -7
  23. // There are some wrinkles illustrated below.
  24. // Most uses of Format and Parse use constant layout strings such as
  25. // the ones defined in this package, but the interface is flexible,
  26. // as these examples show.
  27. // Define a helper function to make the examples' output look nice.
  28. do := func(name, layout, want string) {
  29. got := t.Format(layout)
  30. if want != got {
  31. fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)
  32. return
  33. }
  34. fmt.Printf("%-15s %q gives %q\n", name, layout, got)
  35. }
  36. // Print a header in our output.
  37. fmt.Printf("\nFormats:\n\n")
  38. // A simple starter example.
  39. do("Basic", "Mon Jan 2 15:04:05 MST 2006", "Sat Mar 7 11:06:39 PST 2015")
  40. // For fixed-width printing of values, such as the date, that may be one or
  41. // two characters (7 vs. 07), use an _ instead of a space in the layout string.
  42. // Here we print just the day, which is 2 in our layout string and 7 in our
  43. // value.
  44. do("No pad", "<2>", "<7>")
  45. // An underscore represents a space pad, if the date only has one digit.
  46. do("Spaces", "<_2>", "< 7>")
  47. // A "0" indicates zero padding for single-digit values.
  48. do("Zeros", "<02>", "<07>")
  49. // If the value is already the right width, padding is not used.
  50. // For instance, the second (05 in the reference time) in our value is 39,
  51. // so it doesn't need padding, but the minutes (04, 06) does.
  52. do("Suppressed pad", "04:05", "06:39")
  53. // The predefined constant Unix uses an underscore to pad the day.
  54. // Compare with our simple starter example.
  55. do("Unix", time.UnixDate, "Sat Mar 7 11:06:39 PST 2015")
  56. // The hour of the reference time is 15, or 3PM. The layout can express
  57. // it either way, and since our value is the morning we should see it as
  58. // an AM time. We show both in one format string. Lower case too.
  59. do("AM/PM", "3PM==3pm==15h", "11AM==11am==11h")
  60. // When parsing, if the seconds value is followed by a decimal point
  61. // and some digits, that is taken as a fraction of a second even if
  62. // the layout string does not represent the fractional second.
  63. // Here we add a fractional second to our time value used above.
  64. t, err = time.Parse(time.UnixDate, "Sat Mar 7 11:06:39.1234 PST 2015")
  65. if err != nil {
  66. panic(err)
  67. }
  68. // It does not appear in the output if the layout string does not contain
  69. // a representation of the fractional second.
  70. do("No fraction", time.UnixDate, "Sat Mar 7 11:06:39 PST 2015")
  71. // Fractional seconds can be printed by adding a run of 0s or 9s after
  72. // a decimal point in the seconds value in the layout string.
  73. // If the layout digits are 0s, the fractional second is of the specified
  74. // width. Note that the output has a trailing zero.
  75. do("0s for fraction", "15:04:05.00000", "11:06:39.12340")
  76. // If the fraction in the layout is 9s, trailing zeros are dropped.
  77. do("9s for fraction", "15:04:05.99999999", "11:06:39.1234")
  78. // Output:
  79. // default format: 2015-03-07 11:06:39 -0800 PST
  80. // Unix format: Sat Mar 7 11:06:39 PST 2015
  81. // Same, in UTC: Sat Mar 7 19:06:39 UTC 2015
  82. //
  83. // Formats:
  84. //
  85. // Basic "Mon Jan 2 15:04:05 MST 2006" gives "Sat Mar 7 11:06:39 PST 2015"
  86. // No pad "<2>" gives "<7>"
  87. // Spaces "<_2>" gives "< 7>"
  88. // Zeros "<02>" gives "<07>"
  89. // Suppressed pad "04:05" gives "06:39"
  90. // Unix "Mon Jan _2 15:04:05 MST 2006" gives "Sat Mar 7 11:06:39 PST 2015"
  91. // AM/PM "3PM==3pm==15h" gives "11AM==11am==11h"
  92. // No fraction "Mon Jan _2 15:04:05 MST 2006" gives "Sat Mar 7 11:06:39 PST 2015"
  93. // 0s for fraction "15:04:05.00000" gives "11:06:39.12340"
  94. // 9s for fraction "15:04:05.99999999" gives "11:06:39.1234"

func (*Time) GobDecode

  1. func (t *Time) GobDecode(data []byte) error

GobDecode implements the gob.GobDecoder interface.

func (Time) GobEncode

  1. func (t Time) GobEncode() ([]byte, error)

GobEncode implements the gob.GobEncoder interface.

func (Time) Hour

  1. func (t Time) Hour() int

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

func (Time) ISOWeek

  1. func (t Time) ISOWeek() (year, week 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) In

  1. func (t Time) In(loc *Location) Time

In returns t with the location information set to loc.

In panics if loc is nil.

func (Time) IsZero

  1. func (t Time) IsZero() bool

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

func (Time) Local

  1. func (t Time) Local() Time

Local returns t with the location set to local time.

func (Time) Location

  1. func (t Time) Location() *Location

Location returns the time zone information associated with t.

func (Time) MarshalBinary

  1. func (t Time) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface.

func (Time) MarshalJSON

  1. func (t Time) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface. The time is a quoted string
in RFC 3339 format, with sub-second precision added if present.

func (Time) MarshalText

  1. func (t Time) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface. The time is
formatted in RFC 3339 format, with sub-second precision added if present.

func (Time) Minute

  1. func (t Time) Minute() int

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

func (Time) Month

  1. func (t Time) Month() Month

Month returns the month of the year specified by t.

func (Time) Nanosecond

  1. func (t Time) Nanosecond() int

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

func (Time) Round

  1. 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. Thus, Round(Hour) may return a
time with a non-zero minute, depending on the time’s Location.


Example:

  1. t := time.Date(0, 0, 0, 12, 15, 30, 918273645, time.UTC)
  2. round := []time.Duration{
  3. time.Nanosecond,
  4. time.Microsecond,
  5. time.Millisecond,
  6. time.Second,
  7. 2 * time.Second,
  8. time.Minute,
  9. 10 * time.Minute,
  10. time.Hour,
  11. }
  12. for _, d := range round {
  13. fmt.Printf("t.Round(%6s) = %s\n", d, t.Round(d).Format("15:04:05.999999999"))
  14. }
  15. // Output:
  16. // t.Round( 1ns) = 12:15:30.918273645
  17. // t.Round( 1µs) = 12:15:30.918274
  18. // t.Round( 1ms) = 12:15:30.918
  19. // t.Round( 1s) = 12:15:31
  20. // t.Round( 2s) = 12:15:30
  21. // t.Round( 1m0s) = 12:16:00
  22. // t.Round( 10m0s) = 12:20:00
  23. // t.Round(1h0m0s) = 12:00:00

func (Time) Second

  1. func (t Time) Second() int

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

func (Time) String

  1. func (t Time) String() string

String returns the time formatted using the format string

  1. "2006-01-02 15:04:05.999999999 -0700 MST"

If the time has a monotonic clock reading, the returned string includes a final
field “m=±“, where value is the monotonic clock reading formatted as a
decimal number of seconds.

The returned string is meant for debugging; for a stable serialized
representation, use t.MarshalText, t.MarshalBinary, or t.Format with an explicit
format string.


Example:

  1. timeWithNanoseconds := time.Date(2000, 2, 1, 12, 13, 14, 15, time.UTC)
  2. withNanoseconds := timeWithNanoseconds.String()
  3. timeWithoutNanoseconds := time.Date(2000, 2, 1, 12, 13, 14, 0, time.UTC)
  4. withoutNanoseconds := timeWithoutNanoseconds.String()
  5. fmt.Printf("withNanoseconds = %v\n", string(withNanoseconds))
  6. fmt.Printf("withoutNanoseconds = %v\n", string(withoutNanoseconds))
  7. // Output:
  8. // withNanoseconds = 2000-02-01 12:13:14.000000015 +0000 UTC
  9. // withoutNanoseconds = 2000-02-01 12:13:14 +0000 UTC

func (Time) Sub

  1. 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).


Example:

  1. start := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
  2. end := time.Date(2000, 1, 1, 12, 0, 0, 0, time.UTC)
  3. difference := end.Sub(start)
  4. fmt.Printf("difference = %v\n", difference)
  5. // Output:
  6. // difference = 12h0m0s

func (Time) Truncate

  1. 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. Thus, Truncate(Hour) may
return a time with a non-zero minute, depending on the time’s Location.


Example:

  1. t, _ := time.Parse("2006 Jan 02 15:04:05", "2012 Dec 07 12:15:30.918273645")
  2. trunc := []time.Duration{
  3. time.Nanosecond,
  4. time.Microsecond,
  5. time.Millisecond,
  6. time.Second,
  7. 2 * time.Second,
  8. time.Minute,
  9. 10 * time.Minute,
  10. }
  11. for _, d := range trunc {
  12. fmt.Printf("t.Truncate(%5s) = %s\n", d, t.Truncate(d).Format("15:04:05.999999999"))
  13. }
  14. // To round to the last midnight in the local timezone, create a new Date.
  15. midnight := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)
  16. _ = midnight
  17. // Output:
  18. // t.Truncate( 1ns) = 12:15:30.918273645
  19. // t.Truncate( 1µs) = 12:15:30.918273
  20. // t.Truncate( 1ms) = 12:15:30.918
  21. // t.Truncate( 1s) = 12:15:30
  22. // t.Truncate( 2s) = 12:15:30
  23. // t.Truncate( 1m0s) = 12:15:00
  24. // t.Truncate(10m0s) = 12:10:00

func (Time) UTC

  1. func (t Time) UTC() Time

UTC returns t with the location set to UTC.

func (Time) Unix

  1. func (t Time) Unix() int64

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


Example:

  1. // 1 billion seconds of Unix, three ways.
  2. fmt.Println(time.Unix(1e9, 0).UTC()) // 1e9 seconds
  3. fmt.Println(time.Unix(0, 1e18).UTC()) // 1e18 nanoseconds
  4. fmt.Println(time.Unix(2e9, -1e18).UTC()) // 2e9 seconds - 1e18 nanoseconds
  5. t := time.Date(2001, time.September, 9, 1, 46, 40, 0, time.UTC)
  6. fmt.Println(t.Unix()) // seconds since 1970
  7. fmt.Println(t.UnixNano()) // nanoseconds since 1970
  8. // Output:
  9. // 2001-09-09 01:46:40 +0000 UTC
  10. // 2001-09-09 01:46:40 +0000 UTC
  11. // 2001-09-09 01:46:40 +0000 UTC
  12. // 1000000000
  13. // 1000000000000000000

func (Time) UnixNano

  1. 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) UnmarshalBinary

  1. func (t *Time) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.

func (*Time) UnmarshalJSON

  1. func (t *Time) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface. The time is expected to
be a quoted string in RFC 3339 format.

func (*Time) UnmarshalText

  1. func (t *Time) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. The time is
expected to be in RFC 3339 format.

func (Time) Weekday

  1. func (t Time) Weekday() Weekday

Weekday returns the day of the week specified by t.

func (Time) Year

  1. func (t Time) Year() int

Year returns the year in which t occurs.

func (Time) YearDay

  1. 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.

func (Time) Zone

  1. func (t Time) Zone() (name string, offset int)

Zone computes the time zone in effect at time t, returning the abbreviated name
of the zone (such as “CET”) and its offset in seconds east of UTC.

type Timer

  1. type Timer struct {
  2. C <-chan Time
  3. // contains filtered or unexported fields
  4. }

The Timer type represents a single event. When the Timer expires, the current
time will be sent on C, unless the Timer was created by AfterFunc. A Timer must
be created with NewTimer or AfterFunc.

func AfterFunc

  1. func AfterFunc(d Duration, f func()) *Timer

AfterFunc waits for the duration to elapse and then calls f in its own
goroutine. It returns a Timer that can be used to cancel the call using its Stop
method.

func NewTimer

  1. func NewTimer(d Duration) *Timer

NewTimer creates a new Timer that will send the current time on its channel
after at least duration d.

func (*Timer) Reset

  1. func (t *Timer) Reset(d Duration) bool

Reset changes the timer to expire after duration d. It returns true if the timer
had been active, false if the timer had expired or been stopped.

Resetting a timer must take care not to race with the send into t.C that happens
when the current timer expires. If a program has already received a value from
t.C, the timer is known to have expired, and t.Reset can be used directly. If a
program has not yet received a value from t.C, however, the timer must be
stopped and—if Stop reports that the timer expired before being stopped—the
channel explicitly drained:

  1. if !t.Stop() {
  2. <-t.C
  3. }
  4. t.Reset(d)

This should not be done concurrent to other receives from the Timer’s channel.

Note that it is not possible to use Reset’s return value correctly, as there is
a race condition between draining the channel and the new timer expiring. Reset
should always be invoked on stopped or expired channels, as described above. The
return value exists to preserve compatibility with existing programs.

func (*Timer) Stop

  1. func (t *Timer) Stop() bool

Stop prevents the Timer from firing. It returns true if the call stops the
timer, false if the timer has already expired or been stopped. Stop does not
close the channel, to prevent a read from the channel succeeding incorrectly.

To prevent a timer created with NewTimer from firing after a call to Stop, check
the return value and drain the channel. For example, assuming the program has
not received from t.C already:

  1. if !t.Stop() {
  2. <-t.C
  3. }

This cannot be done concurrent to other receives from the Timer’s channel.

For a timer created with AfterFunc(d, f), if t.Stop returns false, then the
timer has already expired and the function f has been started in its own
goroutine; Stop does not wait for f to complete before returning. If the caller
needs to know whether f is completed, it must coordinate with f explicitly.

type Weekday

  1. type Weekday int

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

  1. const (
  2. Sunday Weekday = iota
  3. Monday
  4. Tuesday
  5. Wednesday
  6. Thursday
  7. Friday
  8. Saturday
  9. )

func (Weekday) String

  1. func (d Weekday) String() string

String returns the English name of the day (“Sunday”, “Monday”, …).