time
Index
- func After(d Duration) <-chan Time
- func Tick(d Duration) <-chan Time
- func ParseDuration(s string) (Duration, error)
- func Since(t Time) Duration
- func Until(t Time) Duration
- func FixedZone(name string, offset int) *Location
- func LoadLocation(name string) (*Location, error)
- func LoadLocationFromTZData(name string, data []byte) (*Location, error)
- func NewTicker(d Duration) *Ticker
- 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 AfterFunc(d Duration, f func()) *Timer
- func NewTimer(d Duration) *Timer
- type Duration
- func ParseDuration(s string) (Duration, error)
- func Since(t Time) Duration
- func Until(t Time) 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 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 (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) AppendFormat(b []byte, layout string) []byte
- 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
Functions
func After
1func 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.
1select {
2case m := <-c:
3 handle(m)
4case <-time.After(10 * time.Second):
5 fmt.Println("timed out")
6}
func Tick
1func 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.
1c := time.Tick(5 * time.Second)
2for next := range c {
3 fmt.Printf("%v %s\n", next, statusUpdate())
4}
func ParseDuration
1func 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".
1hours, _ := time.ParseDuration("10h")
2complex, _ := time.ParseDuration("1h10m10s")
3micro, _ := time.ParseDuration("1µs")
4
5micro2, _ := time.ParseDuration("1us")
6
7fmt.Println(hours)
8fmt.Println(complex)
9fmt.Printf("There are %.0f seconds in %v.\n", complex.Seconds(), complex)
10fmt.Printf("There are %d nanoseconds in %v.\n", micro.Nanoseconds(), micro)
11fmt.Printf("There are %6.2e seconds in %v.\n", micro2.Seconds(), micro)
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
1func Since(t Time) Duration
Since returns the time elapsed since t. It is shorthand for time.Now().Sub(t).
func Until
1func Until(t Time) Duration
Until returns the duration until t. It is shorthand for t.Sub(time.Now()).
func FixedZone
1func FixedZone(name string, offset int) *Location
FixedZone returns a Location that always uses the given zone name and offset (seconds east of UTC).
1loc := time.FixedZone("UTC-8", -8*60*60)
2t := time.Date(2009, time.November, 10, 23, 0, 0, 0, loc)
3fmt.Println("The time is:", t.Format(time.RFC822))
Output
The time is: 10 Nov 09 23:00 UTC-8
func LoadLocation
1func 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”.
LoadLocation looks for the IANA Time Zone database in the following locations in order:
- the directory or uncompressed zip file named by the ZONEINFO environment variable
- on a Unix system, the system standard installation location
- $GOROOT/lib/time/zoneinfo.zip
- the time/tzdata package, if it was imported
1location, err := time.LoadLocation("America/Los_Angeles")
2if err != nil {
3 panic(err)
4}
5
6timeInUTC := time.Date(2018, 8, 30, 12, 0, 0, 0, time.UTC)
7fmt.Println(timeInUTC.In(location))
Output
2018-08-30 05:00:00 -0700 PDT
func LoadLocationFromTZData
1func 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 NewTicker
1func NewTicker(d Duration) *Ticker
NewTicker returns a new Ticker containing a channel that will send the current time on the channel after each tick. The period of the ticks is specified by the duration argument. The ticker will adjust the time interval or drop 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.
1ticker := time.NewTicker(time.Second)
2defer ticker.Stop()
3done := make(chan bool)
4go func() {
5 time.Sleep(10 * time.Second)
6 done <- true
7}()
8for {
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 Date
1func 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.
1t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
2fmt.Printf("Go launched at %s\n", t.Local())
Output
Go launched at 2009-11-10 15:00:00 -0800 PST
func Parse
1func Parse(layout, value string) (Time, error)
Parse parses a formatted string and returns the time value it represents. See the documentation for the constant called Layout to see how to represent the format. The second argument must be parseable using the format string (layout) provided as the first argument.
The example for Time.Format demonstrates the working of the layout string in detail and is a good reference.
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 either a comma or a decimal point followed by a maximal series of digits is parsed as a fractional second. Fractional seconds are truncated to nanosecond precision.
Elements omitted from the layout 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.
For layouts specifying the two-digit year 06, a value NN >= 69 will be treated as 19NN and a value NN < 69 will be treated as 20NN.
The remainder of this comment describes the handling of time zones.
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.
1// longForm shows by example how the reference time would be represented in
2// the desired layout.
3const longForm = "Jan 2, 2006 at 3:04pm (MST)"
4t, _ := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)")
5fmt.Println(t)
6
7// shortForm is another way the reference time would be represented
8// in the desired layout; it has no time zone present.
9// Note: without explicit zone, returns time in UTC.
10const shortForm = "2006-Jan-02"
11t, _ = time.Parse(shortForm, "2013-Feb-03")
12fmt.Println(t)
13
14t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")
15fmt.Println(t)
16t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05+07:00")
17fmt.Println(t)
18_, err := time.Parse(time.RFC3339, time.RFC3339)
19fmt.Println("error", err)
Output
2013-02-03 19:54:00 -0800 PST 2013-02-03 00:00:00 +0000 UTC 2006-01-02 15:04:05 +0000 UTC 2006-01-02 15:04:05 +0700 +0700 error parsing time "2006-01-02T15:04:05Z07:00": extra text: "07:00"
func ParseInLocation
1func 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.
1loc, _ := time.LoadLocation("Europe/Berlin")
2
3// This will look for the name CEST in the Europe/Berlin time zone.
4const longForm = "Jan 2, 2006 at 3:04pm (MST)"
5t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)
6fmt.Println(t)
7
8// Note: without explicit zone, returns time in given location.
9const shortForm = "2006-Jan-02"
10t, _ = time.ParseInLocation(shortForm, "2012-Jul-09", loc)
11fmt.Println(t)
Output
2012-07-09 05:02:00 +0200 CEST 2012-07-09 00:00:00 +0200 CEST
func Unix
1func 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).
1unixTime := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
2fmt.Println(unixTime.Unix())
3t := time.Unix(unixTime.Unix(), 0).UTC()
4fmt.Println(t)
Output
1257894000 2009-11-10 23:00:00 +0000 UTC
func AfterFunc
1func 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
1func NewTimer(d Duration) *Timer
NewTimer creates a new Timer that will send the current time on its channel after at least duration d.
Types
type Duration
1type 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 Abs
1func (d Duration) Abs() Duration
Abs returns the absolute value of d. As a special case, math.MinInt64 is converted to math.MaxInt64.
func Hours
1func (d Duration) Hours() float64
Hours returns the duration as a floating point number of hours.
1h, _ := time.ParseDuration("4h30m")
2fmt.Printf("I've got %.1f hours of work left.", h.Hours())
Output
I've got 4.5 hours of work left.
func Microseconds
1func (d Duration) Microseconds() int64
Microseconds returns the duration as an integer microsecond count.
1u, _ := time.ParseDuration("1s")
2fmt.Printf("One second is %d microseconds.\n", u.Microseconds())
Output
One second is 1000000 microseconds.
func Milliseconds
1func (d Duration) Milliseconds() int64
Milliseconds returns the duration as an integer millisecond count.
1u, _ := time.ParseDuration("1s")
2fmt.Printf("One second is %d milliseconds.\n", u.Milliseconds())
Output
One second is 1000 milliseconds.
func Minutes
1func (d Duration) Minutes() float64
Minutes returns the duration as a floating point number of minutes.
1m, _ := time.ParseDuration("1h30m")
2fmt.Printf("The movie is %.0f minutes long.", m.Minutes())
Output
The movie is 90 minutes long.
func Nanoseconds
1func (d Duration) Nanoseconds() int64
Nanoseconds returns the duration as an integer nanosecond count.
1u, _ := time.ParseDuration("1µs")
2fmt.Printf("One microsecond is %d nanoseconds.\n", u.Nanoseconds())
Output
One microsecond is 1000 nanoseconds.
func Round
1func (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.
1d, err := time.ParseDuration("1h15m30.918273645s")
2if err != nil {
3 panic(err)
4}
5
6round := []time.Duration{
7 time.Nanosecond,
8 time.Microsecond,
9 time.Millisecond,
10 time.Second,
11 2 * time.Second,
12 time.Minute,
13 10 * time.Minute,
14 time.Hour,
15}
16
17for _, r := range round {
18 fmt.Printf("d.Round(%6s) = %s\n", r, d.Round(r).String())
19}
Output
d.Round( 1ns) = 1h15m30.918273645s d.Round( 1µs) = 1h15m30.918274s d.Round( 1ms) = 1h15m30.918s d.Round( 1s) = 1h15m31s d.Round( 2s) = 1h15m30s d.Round( 1m0s) = 1h16m0s d.Round( 10m0s) = 1h20m0s d.Round(1h0m0s) = 1h0m0s
func Seconds
1func (d Duration) Seconds() float64
Seconds returns the duration as a floating point number of seconds.
1m, _ := time.ParseDuration("1m30s")
2fmt.Printf("Take off in t-%.0f seconds.", m.Seconds())
Output
Take off in t-90 seconds.
func String
1func (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.
1fmt.Println(1*time.Hour + 2*time.Minute + 300*time.Millisecond)
2fmt.Println(300 * time.Millisecond)
Output
1h2m0.3s 300ms
func Truncate
1func (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.
1d, err := time.ParseDuration("1h15m30.918273645s")
2if err != nil {
3 panic(err)
4}
5
6trunc := []time.Duration{
7 time.Nanosecond,
8 time.Microsecond,
9 time.Millisecond,
10 time.Second,
11 2 * time.Second,
12 time.Minute,
13 10 * time.Minute,
14 time.Hour,
15}
16
17for _, t := range trunc {
18 fmt.Printf("d.Truncate(%6s) = %s\n", t, d.Truncate(t).String())
19}
Output
d.Truncate( 1ns) = 1h15m30.918273645s d.Truncate( 1µs) = 1h15m30.918273s d.Truncate( 1ms) = 1h15m30.918s d.Truncate( 1s) = 1h15m30s d.Truncate( 2s) = 1h15m30s d.Truncate( 1m0s) = 1h15m0s d.Truncate( 10m0s) = 1h10m0s d.Truncate(1h0m0s) = 1h0m0s
type Ticker
1type Ticker struct {
2 C <-chan Time // The channel on which the ticks are delivered.
3
4}
A Ticker holds a channel that delivers “ticks” of a clock at intervals.
func Reset
1func (t *Ticker) Reset(d Duration)
Reset stops a ticker and resets its period to the specified duration. The next tick will arrive after the new period elapses. The duration d must be greater than zero; if not, Reset will panic.
func Stop
1func (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 concurrent goroutine reading from the channel from seeing an erroneous "tick".
type Time
1type Time struct {
2}
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.
Representations of a Time value saved by the GobEncode, MarshalBinary, MarshalJSON, and MarshalText methods store the Time.Location’s offset, but not the location name. They therefore lose information about Daylight Saving Time.
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 Add
1func (t Time) Add(d Duration) Time
Add returns the time t+d.
1start := time.Date(2009, 1, 1, 12, 0, 0, 0, time.UTC)
2afterTenSeconds := start.Add(time.Second * 10)
3afterTenMinutes := start.Add(time.Minute * 10)
4afterTenHours := start.Add(time.Hour * 10)
5afterTenDays := start.Add(time.Hour * 24 * 10)
6
7fmt.Printf("start = %v\n", start)
8fmt.Printf("start.Add(time.Second * 10) = %v\n", afterTenSeconds)
9fmt.Printf("start.Add(time.Minute * 10) = %v\n", afterTenMinutes)
10fmt.Printf("start.Add(time.Hour * 10) = %v\n", afterTenHours)
11fmt.Printf("start.Add(time.Hour * 24 * 10) = %v\n", afterTenDays)
Output
start = 2009-01-01 12:00:00 +0000 UTC start.Add(time.Second * 10) = 2009-01-01 12:00:10 +0000 UTC start.Add(time.Minute * 10) = 2009-01-01 12:10:00 +0000 UTC start.Add(time.Hour * 10) = 2009-01-01 22:00:00 +0000 UTC start.Add(time.Hour * 24 * 10) = 2009-01-11 12:00:00 +0000 UTC
func AddDate
1func (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.
1start := time.Date(2009, 1, 1, 0, 0, 0, 0, time.UTC)
2oneDayLater := start.AddDate(0, 0, 1)
3oneMonthLater := start.AddDate(0, 1, 0)
4oneYearLater := start.AddDate(1, 0, 0)
5
6fmt.Printf("oneDayLater: start.AddDate(0, 0, 1) = %v\n", oneDayLater)
7fmt.Printf("oneMonthLater: start.AddDate(0, 1, 0) = %v\n", oneMonthLater)
8fmt.Printf("oneYearLater: start.AddDate(1, 0, 0) = %v\n", oneYearLater)
Output
oneDayLater: start.AddDate(0, 0, 1) = 2009-01-02 00:00:00 +0000 UTC oneMonthLater: start.AddDate(0, 1, 0) = 2009-02-01 00:00:00 +0000 UTC oneYearLater: start.AddDate(1, 0, 0) = 2010-01-01 00:00:00 +0000 UTC
func After
1func (t Time) After(u Time) bool
After reports whether the time instant t is after u.
1year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
2year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)
3
4isYear3000AfterYear2000 := year3000.After(year2000)
5isYear2000AfterYear3000 := year2000.After(year3000)
6
7fmt.Printf("year3000.After(year2000) = %v\n", isYear3000AfterYear2000)
8fmt.Printf("year2000.After(year3000) = %v\n", isYear2000AfterYear3000)
Output
year3000.After(year2000) = true year2000.After(year3000) = false
func AppendFormat
1func (t Time) AppendFormat(b []byte, layout string) []byte
AppendFormat is like Format but appends the textual representation to b and returns the extended buffer.
1t := time.Date(2017, time.November, 4, 11, 0, 0, 0, time.UTC)
2text := []byte("Time: ")
3
4text = t.AppendFormat(text, time.Kitchen)
5fmt.Println(string(text))
Output
Time: 11:00AM
func Before
1func (t Time) Before(u Time) bool
Before reports whether the time instant t is before u.
1year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
2year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)
3
4isYear2000BeforeYear3000 := year2000.Before(year3000)
5isYear3000BeforeYear2000 := year3000.Before(year2000)
6
7fmt.Printf("year2000.Before(year3000) = %v\n", isYear2000BeforeYear3000)
8fmt.Printf("year3000.Before(year2000) = %v\n", isYear3000BeforeYear2000)
Output
year2000.Before(year3000) = true year3000.Before(year2000) = false
func Clock
1func (t Time) Clock() (hour, min, sec int)
Clock returns the hour, minute, and second within the day specified by t.
func Compare
1func (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 Date
1func (t Time) Date() (year int, month Month, day int)
Date returns the year, month, and day in which t occurs.
1d := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
2year, month, day := d.Date()
3
4fmt.Printf("year = %v\n", year)
5fmt.Printf("month = %v\n", month)
6fmt.Printf("day = %v\n", day)
Output
year = 2000 month = February day = 1
func Day
1func (t Time) Day() int
Day returns the day of the month specified by t.
1d := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
2day := d.Day()
3
4fmt.Printf("day = %v\n", day)
Output
day = 1
func Equal
1func (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 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.
1secondsEastOfUTC := int((8 * time.Hour).Seconds())
2beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)
3
4d1 := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
5d2 := time.Date(2000, 2, 1, 20, 30, 0, 0, beijing)
6
7datesEqualUsingEqualOperator := d1 == d2
8datesEqualUsingFunction := d1.Equal(d2)
9
10fmt.Printf("datesEqualUsingEqualOperator = %v\n", datesEqualUsingEqualOperator)
11fmt.Printf("datesEqualUsingFunction = %v\n", datesEqualUsingFunction)
Output
datesEqualUsingEqualOperator = false datesEqualUsingFunction = true
func Format
1func (t Time) Format(layout string) string
Format returns a textual representation of the time value formatted according to the layout defined by the argument. See the documentation for the constant called Layout to see how to represent the layout format.
The executable example for Time.Format demonstrates the working of the layout string in detail and is a good reference.
1t, err := time.Parse(time.UnixDate, "Wed Feb 25 11:06:39 PST 2015")
2if err != nil {
3 panic(err)
4}
5
6tz, err := time.LoadLocation("Asia/Shanghai")
7if err != nil {
8 panic(err)
9}
10
11fmt.Println("default format:", t)
12
13fmt.Println("Unix format:", t.Format(time.UnixDate))
14
15fmt.Println("Same, in UTC:", t.UTC().Format(time.UnixDate))
16
17fmt.Println("in Shanghai with seconds:", t.In(tz).Format("2006-01-02T15:04:05 -070000"))
18
19fmt.Println("in Shanghai with colon seconds:", t.In(tz).Format("2006-01-02T15:04:05 -07:00:00"))
20
21do := func(name, layout, want string) {
22 got := t.Format(layout)
23 if want != got {
24 fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)
25 return
26 }
27 fmt.Printf("%-16s %q gives %q\n", name, layout, got)
28}
29
30fmt.Printf("\nFormats:\n\n")
31
32do("Basic full date", "Mon Jan 2 15:04:05 MST 2006", "Wed Feb 25 11:06:39 PST 2015")
33do("Basic short date", "2006/01/02", "2015/02/25")
34
35do("AM/PM", "3PM==3pm==15h", "11AM==11am==11h")
36
37t, err = time.Parse(time.UnixDate, "Wed Feb 25 11:06:39.1234 PST 2015")
38if err != nil {
39 panic(err)
40}
41
42do("No fraction", time.UnixDate, "Wed Feb 25 11:06:39 PST 2015")
43
44do("0s for fraction", "15:04:05.00000", "11:06:39.12340")
45
46do("9s for fraction", "15:04:05.99999999", "11:06:39.1234")
Output
default format: 2015-02-25 11:06:39 -0800 PST Unix format: Wed Feb 25 11:06:39 PST 2015 Same, in UTC: Wed Feb 25 19:06:39 UTC 2015 in Shanghai with seconds: 2015-02-26T03:06:39 +080000 in Shanghai with colon seconds: 2015-02-26T03:06:39 +08:00:00 Formats: Basic full date "Mon Jan 2 15:04:05 MST 2006" gives "Wed Feb 25 11:06:39 PST 2015" Basic short date "2006/01/02" gives "2015/02/25" AM/PM "3PM==3pm==15h" gives "11AM==11am==11h" No fraction "Mon Jan _2 15:04:05 MST 2006" gives "Wed Feb 25 11:06:39 PST 2015" 0s for fraction "15:04:05.00000" gives "11:06:39.12340" 9s for fraction "15:04:05.99999999" gives "11:06:39.1234"
1t, err := time.Parse(time.UnixDate, "Sat Mar 7 11:06:39 PST 2015")
2if err != nil {
3 panic(err)
4}
5
6do := func(name, layout, want string) {
7 got := t.Format(layout)
8 if want != got {
9 fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)
10 return
11 }
12 fmt.Printf("%-16s %q gives %q\n", name, layout, got)
13}
14
15do("Unix", time.UnixDate, "Sat Mar 7 11:06:39 PST 2015")
16
17do("No pad", "<2>", "<7>")
18
19do("Spaces", "<_2>", "< 7>")
20
21do("Zeros", "<02>", "<07>")
22
23do("Suppressed pad", "04:05", "06:39")
Output
Unix "Mon Jan _2 15:04:05 MST 2006" gives "Sat Mar 7 11:06:39 PST 2015" No pad "<2>" gives "<7>" Spaces "<_2>" gives "< 7>" Zeros "<02>" gives "<07>" Suppressed pad "04:05" gives "06:39"
func GoString
1func (t Time) GoString() string
GoString implements fmt.GoStringer and formats t to be printed in Go source code.
1t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
2fmt.Println(t.GoString())
3t = t.Add(1 * time.Minute)
4fmt.Println(t.GoString())
5t = t.AddDate(0, 1, 0)
6fmt.Println(t.GoString())
7t, _ = time.Parse("Jan 2, 2006 at 3:04pm (MST)", "Feb 3, 2013 at 7:54pm (UTC)")
8fmt.Println(t.GoString())
Output
time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) time.Date(2009, time.November, 10, 23, 1, 0, 0, time.UTC) time.Date(2009, time.December, 10, 23, 1, 0, 0, time.UTC) time.Date(2013, time.February, 3, 19, 54, 0, 0, time.UTC)
func GobDecode
1func (t *Time) GobDecode(data []byte) error
GobDecode implements the gob.GobDecoder interface.
func GobEncode
1func (t Time) GobEncode() ([]byte, error)
GobEncode implements the gob.GobEncoder interface.
func Hour
1func (t Time) Hour() int
Hour returns the hour within the day specified by t, in the range [0, 23].
func ISOWeek
1func (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 In
1func (t Time) In(loc *Location) Time
In returns a copy of t representing the same time instant, but with the copy's location information set to loc for display purposes.
In panics if loc is nil.
func IsDST
1func (t Time) IsDST() bool
IsDST reports whether the time in the configured location is in Daylight Savings Time.
func IsZero
1func (t Time) IsZero() bool
IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.
func Location
1func (t Time) Location() *Location
Location returns the time zone information associated with t.
func MarshalBinary
1func (t Time) MarshalBinary() ([]byte, error)
MarshalBinary implements the encoding.BinaryMarshaler interface.
func MarshalJSON
1func (t Time) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface. The time is a quoted string in the RFC 3339 format with sub-second precision. If the timestamp cannot be represented as valid RFC 3339 (e.g., the year is out of range), then an error is reported.
func MarshalText
1func (t Time) MarshalText() ([]byte, error)
MarshalText implements the encoding.TextMarshaler interface. The time is formatted in RFC 3339 format with sub-second precision. If the timestamp cannot be represented as valid RFC 3339 (e.g., the year is out of range), then an error is reported.
func Minute
1func (t Time) Minute() int
Minute returns the minute offset within the hour specified by t, in the range [0, 59].
func Nanosecond
1func (t Time) Nanosecond() int
Nanosecond returns the nanosecond offset within the second specified by t, in the range [0, 999999999].
func Round
1func (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.
1t := time.Date(0, 0, 0, 12, 15, 30, 918273645, time.UTC)
2round := []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
13for _, d := range round {
14 fmt.Printf("t.Round(%6s) = %s\n", d, t.Round(d).Format("15:04:05.999999999"))
15}
Output
t.Round( 1ns) = 12:15:30.918273645 t.Round( 1µs) = 12:15:30.918274 t.Round( 1ms) = 12:15:30.918 t.Round( 1s) = 12:15:31 t.Round( 2s) = 12:15:30 t.Round( 1m0s) = 12:16:00 t.Round( 10m0s) = 12:20:00 t.Round(1h0m0s) = 12:00:00
func Second
1func (t Time) Second() int
Second returns the second offset within the minute specified by t, in the range [0, 59].
func String
1func (t Time) String() string
String returns the time formatted using the format string
"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=±
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.
1timeWithNanoseconds := time.Date(2000, 2, 1, 12, 13, 14, 15, time.UTC)
2withNanoseconds := timeWithNanoseconds.String()
3
4timeWithoutNanoseconds := time.Date(2000, 2, 1, 12, 13, 14, 0, time.UTC)
5withoutNanoseconds := timeWithoutNanoseconds.String()
6
7fmt.Printf("withNanoseconds = %v\n", string(withNanoseconds))
8fmt.Printf("withoutNanoseconds = %v\n", string(withoutNanoseconds))
Output
withNanoseconds = 2000-02-01 12:13:14.000000015 +0000 UTC withoutNanoseconds = 2000-02-01 12:13:14 +0000 UTC
func Sub
1func (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).
1start := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
2end := time.Date(2000, 1, 1, 12, 0, 0, 0, time.UTC)
3
4difference := end.Sub(start)
5fmt.Printf("difference = %v\n", difference)
Output
difference = 12h0m0s
func Truncate
1func (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.
1t, _ := time.Parse("2006 Jan 02 15:04:05", "2012 Dec 07 12:15:30.918273645")
2trunc := []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
12for _, d := range trunc {
13 fmt.Printf("t.Truncate(%5s) = %s\n", d, t.Truncate(d).Format("15:04:05.999999999"))
14}
15
16midnight := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)
17_ = midnight
Output
t.Truncate( 1ns) = 12:15:30.918273645 t.Truncate( 1µs) = 12:15:30.918273 t.Truncate( 1ms) = 12:15:30.918 t.Truncate( 1s) = 12:15:30 t.Truncate( 2s) = 12:15:30 t.Truncate( 1m0s) = 12:15:00 t.Truncate(10m0s) = 12:10:00
func Unix
1func (t Time) Unix() int64
Unix returns t as a Unix time, the number of seconds elapsed since January 1, 1970 UTC. The result does not depend on the location associated with t. 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.
1fmt.Println(time.Unix(1e9, 0).UTC())
2fmt.Println(time.Unix(0, 1e18).UTC())
3fmt.Println(time.Unix(2e9, -1e18).UTC())
4
5t := time.Date(2001, time.September, 9, 1, 46, 40, 0, time.UTC)
6fmt.Println(t.Unix())
7fmt.Println(t.UnixNano())
Output
2001-09-09 01:46:40 +0000 UTC 2001-09-09 01:46:40 +0000 UTC 2001-09-09 01:46:40 +0000 UTC 1000000000 1000000000000000000
func UnixMicro
1func (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). The result does not depend on the location associated with t.
func UnixMilli
1func (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). The result does not depend on the location associated with t.
func UnixNano
1func (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. The result does not depend on the location associated with t.
func UnmarshalBinary
1func (t *Time) UnmarshalBinary(data []byte) error
UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
func UnmarshalJSON
1func (t *Time) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface. The time must be a quoted string in the RFC 3339 format.
func UnmarshalText
1func (t *Time) UnmarshalText(data []byte) error
UnmarshalText implements the encoding.TextUnmarshaler interface. The time must be in the RFC 3339 format.
func YearDay
1func (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 Zone
1func (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.
func ZoneBounds
1func (t Time) ZoneBounds() (start, end Time)
ZoneBounds returns the bounds of the time zone in effect at time t. The zone begins at start and the next zone begins at end. If the zone begins at the beginning of time, start will be returned as a zero Time. If the zone goes on forever, end will be returned as a zero Time. The Location of the returned times will be the same as t.
type Timer
1type Timer struct {
2 C <-chan Time
3}
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 Reset
1func (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.
For a Timer created with NewTimer, Reset should be invoked only on stopped or expired timers with drained channels.
If a program has already received a value from t.C, the timer is known to have expired and the channel drained, so 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:
if !t.Stop() {
<-t.C
}
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.
For a Timer created with AfterFunc(d, f), Reset either reschedules when f will run, in which case Reset returns true, or schedules f to run again, in which case it returns false. When Reset returns false, Reset neither waits for the prior f to complete before returning nor does it guarantee that the subsequent goroutine running f does not run concurrently with the prior one. If the caller needs to know whether the prior execution of f is completed, it must coordinate with f explicitly.
func Stop
1func (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 ensure the channel is empty 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:
if !t.Stop() {
<-t.C
}
This cannot be done concurrent to other receives from the Timer’s channel or other calls to the Timer’s Stop method.
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.