time - The Go Programming Language

Golang

Package time

import "time"
Overview
Index
Examples

Overview ?

Overview ?

Package time provides functionality for measuring and displaying time.

The calendrical calculations always assume a Gregorian calendar.

Index

Constants
func After(d Duration) <-chan Time
func Sleep(d Duration)
func Tick(d Duration) <-chan Time
type Duration
    func ParseDuration(s string) (Duration, error)
    func Since(t Time) Duration
    func (d Duration) Hours() float64
    func (d Duration) Minutes() float64
    func (d Duration) Nanoseconds() int64
    func (d Duration) Seconds() float64
    func (d Duration) String() string
type Location
    func FixedZone(name string, offset int) *Location
    func LoadLocation(name string) (*Location, error)
    func (l *Location) String() string
type Month
    func (m Month) String() string
type ParseError
    func (e *ParseError) Error() string
type Ticker
    func NewTicker(d Duration) *Ticker
    func (t *Ticker) Stop()
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 Unix(sec int64, nsec 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) Before(u Time) bool
    func (t Time) Clock() (hour, min, sec 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) GobDecode(buf []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) IsZero() bool
    func (t Time) Local() Time
    func (t Time) Location() *Location
    func (t Time) MarshalJSON() ([]byte, error)
    func (t Time) Minute() int
    func (t Time) Month() Month
    func (t Time) Nanosecond() int
    func (t Time) Second() int
    func (t Time) String() string
    func (t Time) Sub(u Time) Duration
    func (t Time) UTC() Time
    func (t Time) Unix() int64
    func (t Time) UnixNano() int64
    func (t *Time) UnmarshalJSON(data []byte) (err error)
    func (t Time) Weekday() Weekday
    func (t Time) Year() int
    func (t Time) Zone() (name string, offset int)
type Timer
    func AfterFunc(d Duration, f func()) *Timer
    func NewTimer(d Duration) *Timer
    func (t *Timer) Stop() (ok bool)
type Weekday
    func (d Weekday) String() string

Examples

After
Date
Duration
Month
Sleep
Tick

Package files

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

Constants

const (
    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"
)

These are predefined layouts for use in Time.Format. The standard time used in the layouts is:

Mon Jan 2 15:04:05 MST 2006

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

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

To define your own format, write down what the standard time would look like formatted your way; see the values of constants like ANSIC, StampMicro or Kitchen for examples.

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:

-0700  hhmm
-07:00 hh:mm

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

func After

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.

? Example

? Example

Code:

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

func Sleep

func Sleep(d Duration)

Sleep pauses the current goroutine for the duration d.

? Example

? Example

Code:

time.Sleep(100 * time.Millisecond)

func Tick

func Tick(d Duration) <-chan Time

Tick is a convenience wrapper for NewTicker providing access to the ticking channel only. Useful for clients that have no need to shut down the ticker.

? Example

? Example

Code:

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

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.

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

? Example

? Example

Code:

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

func ParseDuration

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

func Since

func Since(t Time) Duration

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

func (Duration) Hours

func (d Duration) Hours() float64

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

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) Seconds

func (d Duration) Seconds() float64

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

func (Duration) String

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 0, with no unit.

type Location

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

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.

var Local *Location = &localLoc

Local represents the system's local time zone.

var UTC *Location = &utcLoc

UTC represents Universal Coordinated Time (UTC).

func FixedZone

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

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 (*Location) String

func (l *Location) String() string

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

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
)

? Example

? Example

Code:

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

func (Month) String

func (m Month) String() string

String returns the English name of the month ("January", "February", ...).

type ParseError

type ParseError struct {
    Layout     string
    Value      string
    LayoutElem string
    ValueElem  string
    Message    string
}

ParseError describes a problem parsing a time string.

func (*ParseError) Error

func (e *ParseError) Error() string

Error returns the string representation of a ParseError.

type Ticker

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

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

func NewTicker

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.

func (*Ticker) Stop

func (t *Ticker) Stop()

Stop turns off a ticker. After Stop, no more ticks will be sent.

type Time

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

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.

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.

func Date

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

Date returns the Time corresponding to

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

? Example

Code:

t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
fmt.Printf("Go launched at %s\n", t.Local())

Output:

Go launched at 2009-11-10 15:00:00 -0800 PST

func Now

func Now() Time

Now returns the current local time.

func Parse

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 the representation of the standard time,

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

which is then used to describe the string to be parsed. Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard representations. For more information about the formats and the definition of the standard time, see the documentation for ANSIC.

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. Years must be in the range 0000..9999. The day of the week is checked for syntax but it is otherwise ignored.

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

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() (hour, min, sec int)

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

func (Time) Date

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

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

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. Two times can be equal even if they are in different locations. For example, 6:00 +0200 CEST and 4:00 UTC are Equal. This comparison is different from using t == u, which also compares the locations.

func (Time) Format

func (t Time) Format(layout string) string

Format returns a textual representation of the time value formatted according to layout. The layout defines the format by showing the representation of the standard time,

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

which is then used to describe the time to be formatted. Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard representations. For more information about the formats and the definition of the standard time, see the documentation for ANSIC.

func (*Time) GobDecode

func (t *Time) GobDecode(buf []byte) error

GobDecode implements the gob.GobDecoder interface.

func (Time) GobEncode

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

GobEncode implements the gob.GobEncoder interface.

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

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

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

func (t Time) Local() Time

Local returns t with the location set to local time.

func (Time) Location

func (t Time) Location() *Location

Location returns the time zone information associated with t.

func (Time) MarshalJSON

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

MarshalJSON implements the json.Marshaler interface. Time is formatted as RFC3339.

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

String returns the time formatted using the format string

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

func (Time) Sub

func (t Time) Sub(u Time) Duration

Sub returns the duration t-u. To compute t-d for a duration d, use t.Add(-d).

func (Time) UTC

func (t Time) UTC() Time

UTC returns t with the location set to UTC.

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.

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. Note that this means the result of calling UnixNano on the zero Time is undefined.

func (*Time) UnmarshalJSON

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

UnmarshalJSON implements the json.Unmarshaler interface. Time is expected in RFC3339 format.

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) Zone

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

type Timer struct {
    C <-chan Time
    // contains filtered or unexported fields
}

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.

func AfterFunc

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

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) Stop

func (t *Timer) Stop() (ok bool)

Stop prevents the Timer from firing. It returns true if the call stops the timer, false if the timer has already expired or stopped.

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
)

func (Weekday) String

func (d Weekday) String() string

String returns the English name of the day ("Sunday", "Monday", ...).