time
packagestandard libraryThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
Documentation¶
Overview¶
Package time provides functionality for measuring and displaying time.
The calendrical calculations always assume a Gregorian calendar, withno leap seconds.
Monotonic Clocks¶
Operating systems provide both a “wall clock,” which is subject tochanges for clock synchronization, and a “monotonic clock,” which isnot. The general rule is that the wall clock is for telling time andthe monotonic clock is for measuring time. Rather than split the API,in this package the Time returned bytime.Now contains both a wallclock reading and a monotonic clock reading; later time-tellingoperations use the wall clock reading, but later time-measuringoperations, specifically comparisons and subtractions, use themonotonic clock reading.
For example, this code always computes a positive elapsed time ofapproximately 20 milliseconds, even if the wall clock is changed duringthe operation being timed:
start := time.Now()... operation that takes 20 milliseconds ...t := time.Now()elapsed := t.Sub(start)
Other idioms, such astime.Since(start),time.Until(deadline), andtime.Now().Before(deadline), are similarly robust against wall clockresets.
The rest of this section gives the precise details of how operationsuse monotonic clocks, but understanding those details is not requiredto 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 toboth 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 timecomputations, 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 interpretationof 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 operationst.After(u), t.Before(u), t.Equal(u), t.Compare(u), and t.Sub(u) are carried outusing the monotonic clock readings alone, ignoring the wall clockreadings. If either t or u contains no monotonic clock reading, theseoperations fall back to using the wall clock readings.
On some systems the monotonic clock will stop if the computer goes to sleep.On such a system, t.Sub(u) may not accurately reflect the actualtime that passed between t and u. The same applies to other functions andmethods that subtract times, such asSince,Until,Time.Before,Time.After,Time.Add,Time.Equal andTime.Compare. In some cases, you may need to stripthe monotonic clock to get accurate results.
Because the monotonic clock reading has no meaning outsidethe current process, the serialized forms generated by t.GobEncode,t.MarshalBinary, t.MarshalJSON, and t.MarshalText omit the monotonicclock reading, and t.Format provides no format for it. Similarly, theconstructorstime.Date,time.Parse,time.ParseInLocation, andtime.Unix,as well as the unmarshalers t.GobDecode, t.UnmarshalBinary.t.UnmarshalJSON, and t.UnmarshalText always create times withno monotonic clock reading.
The monotonic clock reading exists only inTime values. It is nota part ofDuration values or the Unix times returned by t.Unix andfriends.
Note that the Go == operator compares not just the time instant butalso theLocation and the monotonic clock reading. See thedocumentation for the Time type for a discussion of equalitytesting for Time values.
For debugging, the result of t.String does include the monotonicclock reading if present. If t != u because of different monotonic clock readings,that difference will be visible when printing t.String() and u.String().
Timer Resolution¶
Timer resolution varies depending on the Go runtime, the operating systemand the underlying hardware.On Unix, the resolution is ~1ms.On Windows version 1803 and newer, the resolution is ~0.5ms.On older Windows versions, the default resolution is ~16ms, buta higher resolution may be requested usinggolang.org/x/sys/windows.TimeBeginPeriod.
Index¶
- Constants
- func After(d Duration) <-chan Time
- func Sleep(d Duration)
- func Tick(d Duration) <-chan Time
- type Duration
- func (d Duration) Abs() Duration
- func (d Duration) Hours() float64
- func (d Duration) Microseconds() int64
- func (d Duration) Milliseconds() int64
- func (d Duration) Minutes() float64
- func (d Duration) Nanoseconds() int64
- func (d Duration) Round(m Duration) Duration
- func (d Duration) Seconds() float64
- func (d Duration) String() string
- func (d Duration) Truncate(m Duration) Duration
- type Location
- type Month
- type ParseError
- type Ticker
- type Time
- func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
- func Now() Time
- func Parse(layout, value string) (Time, error)
- func ParseInLocation(layout, value string, loc *Location) (Time, error)
- func Unix(sec int64, nsec int64) Time
- func UnixMicro(usec int64) Time
- func UnixMilli(msec int64) Time
- func (t Time) Add(d Duration) Time
- func (t Time) AddDate(years int, months int, days int) Time
- func (t Time) After(u Time) bool
- func (t Time) AppendBinary(b []byte) ([]byte, error)
- func (t Time) AppendFormat(b []byte, layout string) []byte
- func (t Time) AppendText(b []byte) ([]byte, error)
- func (t Time) Before(u Time) bool
- func (t Time) Clock() (hour, min, sec int)
- func (t Time) Compare(u Time) int
- func (t Time) Date() (year int, month Month, day int)
- func (t Time) Day() int
- func (t Time) Equal(u Time) bool
- func (t Time) Format(layout string) string
- func (t Time) GoString() string
- func (t *Time) GobDecode(data []byte) error
- func (t Time) GobEncode() ([]byte, error)
- func (t Time) Hour() int
- func (t Time) ISOWeek() (year, week int)
- func (t Time) In(loc *Location) Time
- func (t Time) IsDST() bool
- func (t Time) IsZero() bool
- func (t Time) Local() Time
- func (t Time) Location() *Location
- func (t Time) MarshalBinary() ([]byte, error)
- func (t Time) MarshalJSON() ([]byte, error)
- func (t Time) MarshalText() ([]byte, error)
- func (t Time) Minute() int
- func (t Time) Month() Month
- func (t Time) Nanosecond() int
- func (t Time) Round(d Duration) Time
- func (t Time) Second() int
- func (t Time) String() string
- func (t Time) Sub(u Time) Duration
- func (t Time) Truncate(d Duration) Time
- func (t Time) UTC() Time
- func (t Time) Unix() int64
- func (t Time) UnixMicro() int64
- func (t Time) UnixMilli() int64
- func (t Time) UnixNano() int64
- func (t *Time) UnmarshalBinary(data []byte) error
- func (t *Time) UnmarshalJSON(data []byte) error
- func (t *Time) UnmarshalText(data []byte) error
- func (t Time) Weekday() Weekday
- func (t Time) Year() int
- func (t Time) YearDay() int
- func (t Time) Zone() (name string, offset int)
- func (t Time) ZoneBounds() (start, end Time)
- type Timer
- type Weekday
Examples¶
- After
- Date
- Duration
- Duration.Abs
- Duration.Hours
- Duration.Microseconds
- Duration.Milliseconds
- Duration.Minutes
- Duration.Nanoseconds
- Duration.Round
- Duration.Seconds
- Duration.String
- Duration.Truncate
- FixedZone
- LoadLocation
- Location
- Month
- NewTicker
- Parse
- ParseDuration
- ParseInLocation
- Since
- Sleep
- Tick
- Time.Add
- Time.AddDate
- Time.After
- Time.AppendBinary
- Time.AppendFormat
- Time.AppendText
- Time.Before
- Time.Date
- Time.Day
- Time.Equal
- Time.Format
- Time.Format (Pad)
- Time.GoString
- Time.Round
- Time.String
- Time.Sub
- Time.Truncate
- Time.Unix
- Unix
- UnixMicro
- UnixMilli
- Until
Constants¶
const (Layout = "01/02 03:04:05PM '06 -0700"// The reference time, in numerical order.ANSIC = "Mon Jan _2 15:04:05 2006"UnixDate = "Mon Jan _2 15:04:05 MST 2006"RubyDate = "Mon Jan 02 15:04:05 -0700 2006"RFC822 = "02 Jan 06 15:04 MST"RFC822Z = "02 Jan 06 15:04 -0700"// RFC822 with numeric zoneRFC850 = "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 zoneRFC3339 = "2006-01-02T15:04:05Z07:00"RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"Kitchen = "3:04PM"// Handy time stamps.Stamp = "Jan _2 15:04:05"StampMilli = "Jan _2 15:04:05.000"StampMicro = "Jan _2 15:04:05.000000"StampNano = "Jan _2 15:04:05.000000000"DateTime = "2006-01-02 15:04:05"DateOnly = "2006-01-02"TimeOnly = "15:04:05")
These are predefined layouts for use inTime.Format andtime.Parse.The reference time used in these layouts is the specific time stamp:
01/02 03:04:05PM '06 -0700
(January 2, 15:04:05, 2006, in time zone seven hours west of GMT).That value is recorded as the constant namedLayout, listed below. As a Unixtime, this is 1136239445. Since MST is GMT-0700, the reference would beprinted by the Unix date command as:
Mon Jan 2 15:04:05 MST 2006
It is a regrettable historic error that the date uses the American conventionof putting the numerical month before the day.
The example for Time.Format demonstrates the working of the layout stringin detail and is a good reference.
Note that theRFC822,RFC850, andRFC1123 formats should be appliedonly to local times. Applying them to UTC times will use "UTC" as thetime zone abbreviation, while strictly speaking those RFCs require theuse of "GMT" in that case.When using theRFC1123 orRFC1123Z formats for parsing, note that theseformats define a leading zero for the day-in-month portion, which is notstrictly allowed byRFC 1123. This will result in an error when parsingdate strings that occur in the first 9 days of a given month.In generalRFC1123Z should be used instead ofRFC1123 for serversthat insist on that format, andRFC3339 should be preferred for new protocols.RFC3339,RFC822,RFC822Z,RFC1123, andRFC1123Z are useful for formatting;when used with time.Parse they do not accept all the time formatspermitted by the RFCs and they do accept time formats not formally defined.TheRFC3339Nano format removes trailing zeros from the seconds fieldand thus may not sort correctly once formatted.
Most programs can use one of the defined constants as the layout passed toFormat or Parse. The rest of this comment can be ignored unless you arecreating a custom layout string.
To define your own format, write down what the reference time would look likeformatted your way; see the values of constants likeANSIC,StampMicro orKitchen for examples. The model is to demonstrate what the reference timelooks like so that the Format and Parse methods can apply the sametransformation to a general time value.
Here is a summary of the components of a layout string. Each element shows byexample the formatting of an element of the reference time. Only these valuesare recognized. Text in the layout string that is not recognized as part ofthe reference time is echoed verbatim during Format and expected to appearverbatim in the input to Parse.
Year: "2006" "06"Month: "Jan" "January" "01" "1"Day of the week: "Mon" "Monday"Day of the month: "2" "_2" "02"Day of the year: "__2" "002"Hour: "15" "3" "03" (PM or AM)Minute: "4" "04"Second: "5" "05"AM/PM mark: "PM"
Numeric time zone offsets format as follows:
"-0700" ±hhmm"-07:00" ±hh:mm"-07" ±hh"-070000" ±hhmmss"-07:00:00" ±hh:mm:ss
Replacing the sign in the format with a Z triggersthe ISO 8601 behavior of printing Z instead of anoffset for the UTC zone. Thus:
"Z0700" Z or ±hhmm"Z07:00" Z or ±hh:mm"Z07" Z or ±hh"Z070000" Z or ±hhmmss"Z07:00:00" Z or ±hh:mm:ss
Within the format string, the underscores in "_2" and "__2" represent spacesthat may be replaced by digits if the following number has multiple digits,for compatibility with fixed-width Unix time formats. A leading zero representsa zero-padded value.
The formats __2 and 002 are space-padded and zero-paddedthree-character day of year; there is no unpadded day of year format.
A comma or decimal point followed by one or more zeros representsa fractional second, printed to the given number of decimal places.A comma or decimal point followed by one or more nines representsa fractional second, printed to the given number of decimal places, withtrailing zeros removed.For example "15:04:05,000" or "15:04:05.000" formats or parses withmillisecond precision.
Some valid layouts are invalid time values for time.Parse, due to formatssuch as _ for space padding and Z for zone information.
const (NanosecondDuration = 1Microsecond = 1000 *NanosecondMillisecond = 1000 *MicrosecondSecond = 1000 *MillisecondMinute = 60 *SecondHour = 60 *Minute)
Common durations. There is no definition for units of Day or largerto avoid confusion across daylight savings time zone transitions.
To count the number of units in aDuration, divide:
second := time.Secondfmt.Print(int64(second/time.Millisecond)) // prints 1000
To convert an integer number of units to a Duration, multiply:
seconds := 10fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
Variables¶
This section is empty.
Functions¶
funcAfter¶
After waits for the duration to elapse and then sends the current timeon the returned channel.It is equivalent toNewTimer(d).C.
Before Go 1.23, this documentation warned that the underlyingTimer would not be recovered by the garbage collector until thetimer fired, and that if efficiency was a concern, code should useNewTimer instead and callTimer.Stop if the timer is no longer needed.As of Go 1.23, the garbage collector can recover unreferenced,unstopped timers. There is no reason to prefer NewTimer when After will do.
Example¶
package mainimport ("fmt""time")var c chan intfunc handle(int) {}func main() {select {case m := <-c:handle(m)case <-time.After(10 * time.Second):fmt.Println("timed out")}}
funcSleep¶
func Sleep(dDuration)
Sleep pauses the current goroutine for at least the duration d.A negative or zero duration causes Sleep to return immediately.
funcTick¶
Tick is a convenience wrapper forNewTicker providing access to the tickingchannel only. Unlike NewTicker, Tick will return nil if d <= 0.
Before Go 1.23, this documentation warned that the underlyingTicker would never be recovered by the garbage collector, and thatif efficiency was a concern, code should use NewTicker instead andcallTicker.Stop when the ticker is no longer needed.As of Go 1.23, the garbage collector can recover unreferencedtickers, even if they haven't been stopped.The Stop method is no longer necessary to help the garbage collector.There is no longer any reason to prefer NewTicker when Tick will do.
Example¶
package mainimport ("fmt""time")func statusUpdate() string { return "" }func main() {c := time.Tick(5 * time.Second)for next := range c {fmt.Printf("%v %s\n", next, statusUpdate())}}
Types¶
typeDuration¶
type Durationint64
A Duration represents the elapsed time between two instantsas an int64 nanosecond count. The representation limits thelargest representable duration to approximately 290 years.
Example¶
package mainimport ("fmt""time")func expensiveCall() {}func main() {t0 := time.Now()expensiveCall()t1 := time.Now()fmt.Printf("The call took %v to run.\n", t1.Sub(t0))}
funcParseDuration¶
ParseDuration parses a duration string.A duration string is a possibly signed sequence ofdecimal numbers, each with optional fraction and a unit suffix,such as "300ms", "-1.5h" or "2h45m".Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
Example¶
package mainimport ("fmt""time")func main() {hours, _ := time.ParseDuration("10h")complex, _ := time.ParseDuration("1h10m10s")micro, _ := time.ParseDuration("1µs")// The package also accepts the incorrect but common prefix u for micro.micro2, _ := time.ParseDuration("1us")fmt.Println(hours)fmt.Println(complex)fmt.Printf("There are %.0f seconds in %v.\n", complex.Seconds(), complex)fmt.Printf("There are %d nanoseconds in %v.\n", micro.Nanoseconds(), micro)fmt.Printf("There are %6.2e seconds in %v.\n", micro2.Seconds(), micro2)}
Output:10h0m0s1h10m10sThere are 4210 seconds in 1h10m10s.There are 1000 nanoseconds in 1µs.There are 1.00e-06 seconds in 1µs.
funcSince¶
Since returns the time elapsed since t.It is shorthand for time.Now().Sub(t).
Example¶
package mainimport ("fmt""time")func expensiveCall() {}func main() {start := time.Now()expensiveCall()elapsed := time.Since(start)fmt.Printf("The call took %v to run.\n", elapsed)}
funcUntil¶added ingo1.8
Until returns the duration until t.It is shorthand for t.Sub(time.Now()).
Example¶
package mainimport ("fmt""math""time")func main() {futureTime := time.Now().Add(5 * time.Second)durationUntil := time.Until(futureTime)fmt.Printf("Duration until future time: %.0f seconds", math.Ceil(durationUntil.Seconds()))}
Output:Duration until future time: 5 seconds
func (Duration)Abs¶added ingo1.19
Abs returns the absolute value of d.As a special case, Duration(math.MinInt64) is converted to Duration(math.MaxInt64),reducing its magnitude by 1 nanosecond.
Example¶
package mainimport ("fmt""math""time")func main() {positiveDuration := 5 * time.SecondnegativeDuration := -3 * time.SecondminInt64CaseDuration := time.Duration(math.MinInt64)absPositive := positiveDuration.Abs()absNegative := negativeDuration.Abs()absSpecial := minInt64CaseDuration.Abs() == time.Duration(math.MaxInt64)fmt.Printf("Absolute value of positive duration: %v\n", absPositive)fmt.Printf("Absolute value of negative duration: %v\n", absNegative)fmt.Printf("Absolute value of MinInt64 equal to MaxInt64: %t\n", absSpecial)}
Output:Absolute value of positive duration: 5sAbsolute value of negative duration: 3sAbsolute value of MinInt64 equal to MaxInt64: true
func (Duration)Hours¶
Hours returns the duration as a floating point number of hours.
Example¶
package mainimport ("fmt""time")func main() {h, _ := time.ParseDuration("4h30m")fmt.Printf("I've got %.1f hours of work left.", h.Hours())}
Output:I've got 4.5 hours of work left.
func (Duration)Microseconds¶added ingo1.13
Microseconds returns the duration as an integer microsecond count.
Example¶
package mainimport ("fmt""time")func main() {u, _ := time.ParseDuration("1s")fmt.Printf("One second is %d microseconds.\n", u.Microseconds())}
Output:One second is 1000000 microseconds.
func (Duration)Milliseconds¶added ingo1.13
Milliseconds returns the duration as an integer millisecond count.
Example¶
package mainimport ("fmt""time")func main() {u, _ := time.ParseDuration("1s")fmt.Printf("One second is %d milliseconds.\n", u.Milliseconds())}
Output:One second is 1000 milliseconds.
func (Duration)Minutes¶
Minutes returns the duration as a floating point number of minutes.
Example¶
package mainimport ("fmt""time")func main() {m, _ := time.ParseDuration("1h30m")fmt.Printf("The movie is %.0f minutes long.", m.Minutes())}
Output:The movie is 90 minutes long.
func (Duration)Nanoseconds¶
Nanoseconds returns the duration as an integer nanosecond count.
Example¶
package mainimport ("fmt""time")func main() {u, _ := time.ParseDuration("1µs")fmt.Printf("One microsecond is %d nanoseconds.\n", u.Nanoseconds())}
Output:One microsecond is 1000 nanoseconds.
func (Duration)Round¶added ingo1.9
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 aDuration,Round returns the maximum (or minimum) duration.If m <= 0, Round returns d unchanged.
Example¶
package mainimport ("fmt""time")func main() {d, err := time.ParseDuration("1h15m30.918273645s")if err != nil {panic(err)}round := []time.Duration{time.Nanosecond,time.Microsecond,time.Millisecond,time.Second,2 * time.Second,time.Minute,10 * time.Minute,time.Hour,}for _, r := range round {fmt.Printf("d.Round(%6s) = %s\n", r, d.Round(r).String())}}
Output:d.Round( 1ns) = 1h15m30.918273645sd.Round( 1µs) = 1h15m30.918274sd.Round( 1ms) = 1h15m30.918sd.Round( 1s) = 1h15m31sd.Round( 2s) = 1h15m30sd.Round( 1m0s) = 1h16m0sd.Round( 10m0s) = 1h20m0sd.Round(1h0m0s) = 1h0m0s
func (Duration)Seconds¶
Seconds returns the duration as a floating point number of seconds.
Example¶
package mainimport ("fmt""time")func main() {m, _ := time.ParseDuration("1m30s")fmt.Printf("Take off in t-%.0f seconds.", m.Seconds())}
Output:Take off in t-90 seconds.
func (Duration)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 onesecond format use a smaller unit (milli-, micro-, or nanoseconds) to ensurethat the leading digit is non-zero. The zero duration formats as 0s.
Example¶
package mainimport ("fmt""time")func main() {fmt.Println(1*time.Hour + 2*time.Minute + 300*time.Millisecond)fmt.Println(300 * time.Millisecond)}
Output:1h2m0.3s300ms
func (Duration)Truncate¶added ingo1.9
Truncate returns the result of rounding d toward zero to a multiple of m.If m <= 0, Truncate returns d unchanged.
Example¶
package mainimport ("fmt""time")func main() {d, err := time.ParseDuration("1h15m30.918273645s")if err != nil {panic(err)}trunc := []time.Duration{time.Nanosecond,time.Microsecond,time.Millisecond,time.Second,2 * time.Second,time.Minute,10 * time.Minute,time.Hour,}for _, t := range trunc {fmt.Printf("d.Truncate(%6s) = %s\n", t, d.Truncate(t).String())}}
Output:d.Truncate( 1ns) = 1h15m30.918273645sd.Truncate( 1µs) = 1h15m30.918273sd.Truncate( 1ms) = 1h15m30.918sd.Truncate( 1s) = 1h15m30sd.Truncate( 2s) = 1h15m30sd.Truncate( 1m0s) = 1h15m0sd.Truncate( 10m0s) = 1h10m0sd.Truncate(1h0m0s) = 1h0m0s
typeLocation¶
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 offsetsin use in a geographical area. For many Locations the time offset variesdepending on whether daylight savings time is in use at the time instant.
Location is used to provide a time zone in a printed Time value and forcalculations involving intervals that may cross daylight savings timeboundaries.
Example¶
package mainimport ("fmt""time")func main() {// China doesn't have daylight saving. It uses a fixed 8 hour offset from UTC.secondsEastOfUTC := int((8 * time.Hour).Seconds())beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)// If the system has a timezone database present, it's possible to load a location// from that, e.g.:// newYork, err := time.LoadLocation("America/New_York")// Creating a time requires a location. Common locations are time.Local and time.UTC.timeInUTC := time.Date(2009, 1, 1, 12, 0, 0, 0, time.UTC)sameTimeInBeijing := time.Date(2009, 1, 1, 20, 0, 0, 0, beijing)// Although the UTC clock time is 1200 and the Beijing clock time is 2000, Beijing is// 8 hours ahead so the two dates actually represent the same instant.timesAreEqual := timeInUTC.Equal(sameTimeInBeijing)fmt.Println(timesAreEqual)}
Output:true
var Local *Location = &localLoc
Local represents the system's local time zone.On Unix systems, Local consults the TZ environmentvariable to find the time zone to use. No TZ meansuse the system default /etc/localtime.TZ="" means use UTC.TZ="foo" means use file foo in the system timezone directory.
var UTC *Location = &utcLoc
UTC represents Universal Coordinated Time (UTC).
funcFixedZone¶
FixedZone returns aLocation that always usesthe given zone name and offset (seconds east of UTC).
Example¶
package mainimport ("fmt""time")func main() {loc := time.FixedZone("UTC-8", -8*60*60)t := time.Date(2009, time.November, 10, 23, 0, 0, 0, loc)fmt.Println("The time is:", t.Format(time.RFC822))}
Output:The time is: 10 Nov 09 23:00 UTC-8
funcLoadLocation¶
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 filein the IANA Time Zone database, such as "America/New_York".
LoadLocation looks for the IANA Time Zone database in the followinglocations 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
Example¶
package mainimport ("fmt""time")func main() {location, err := time.LoadLocation("America/Los_Angeles")if err != nil {panic(err)}timeInUTC := time.Date(2018, 8, 30, 12, 0, 0, 0, time.UTC)fmt.Println(timeInUTC.In(location))}
Output:2018-08-30 05:00:00 -0700 PDT
funcLoadLocationFromTZData¶added ingo1.10
LoadLocationFromTZData returns a Location with the given nameinitialized 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).
typeMonth¶
type Monthint
A Month specifies a month of the year (January = 1, ...).
Example¶
package mainimport ("fmt""time")func main() {_, month, day := time.Now().Date()if month == time.November && day == 10 {fmt.Println("Happy Go day!")}}
typeParseError¶
ParseError describes a problem parsing a time string.
func (*ParseError)Error¶
func (e *ParseError) Error()string
Error returns the string representation of a ParseError.
typeTicker¶
type Ticker struct {C <-chanTime// The channel on which the ticks are delivered.// contains filtered or unexported fields}
A Ticker holds a channel that delivers “ticks” of a clockat intervals.
funcNewTicker¶
NewTicker returns a newTicker containing a channel that will sendthe current time on the channel after each tick. The period of theticks is specified by the duration argument. The ticker will adjustthe time interval or drop ticks to make up for slow receivers.The duration d must be greater than zero; if not, NewTicker willpanic.
Before Go 1.23, the garbage collector did not recovertickers that had not yet expired or been stopped, so code oftenimmediately deferred t.Stop after calling NewTicker, to makethe ticker recoverable when it was no longer needed.As of Go 1.23, the garbage collector can recover unreferencedtickers, even if they haven't been stopped.The Stop method is no longer necessary to help the garbage collector.(Code may of course still want to call Stop to stop the ticker for other reasons.)
Example¶
package mainimport ("fmt""time")func main() {ticker := time.NewTicker(time.Second)defer ticker.Stop()done := make(chan bool)go func() {time.Sleep(10 * time.Second)done <- true}()for {select {case <-done:fmt.Println("Done!")returncase t := <-ticker.C:fmt.Println("Current time: ", t)}}}
typeTime¶
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 oftypetime.Time, not *time.Time.
A Time value can be used by multiple goroutines simultaneously exceptthat the methodsTime.GobDecode,Time.UnmarshalBinary,Time.UnmarshalJSON andTime.UnmarshalText are not concurrency-safe.
Time instants can be compared using theTime.Before,Time.After, andTime.Equal methods.TheTime.Sub method subtracts two instants, producing aDuration.TheTime.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, theTime.IsZero method givesa simple way of detecting a time that has not been initialized explicitly.
Each time has an associatedLocation. The methodsTime.Local,Time.UTC, and Time.In return aTime with a specific Location. Changing the Location of a Time value withthese methods does not change the actual instant it represents, only the timezone in which to interpret it.
Representations of a Time value saved by theTime.GobEncode,Time.MarshalBinary,Time.AppendBinary,Time.MarshalJSON,Time.MarshalText andTime.AppendText methods store theTime.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 optionalreading of the current process's monotonic clock, to provide additional precisionfor 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 theLocation and the monotonic clock reading. Therefore, Time values should notbe used as map or database keys without first guaranteeing that theidentical Location has been set for all values, which can be achievedthrough use of the UTC or Local method, and that the monotonic clock readinghas 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 andcorrectly handles the case when only one of its arguments has a monotonicclock reading.
funcDate¶
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 outsidetheir 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, thechoice of time zone, and therefore the time, is not well-defined.Date returns a time that is correct in one of the two zones involvedin the transition, but it does not guarantee which.
Date panics if loc is nil.
Example¶
package mainimport ("fmt""time")func main() {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
funcParse¶
Parse parses a formatted string and returns the time value it represents.See the documentation for the constant calledLayout to see how torepresent the format. The second argument must be parseable usingthe format string (layout) provided as the first argument.
The example forTime.Format demonstrates the working of the layout stringin detail and is a good reference.
When parsing (only), the input may contain a fractional secondfield immediately after the seconds field, even if the layout does notsignify its presence. In that case either a comma or a decimal pointfollowed 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, whenzero is impossible, one, so parsing "3:04pm" returns the timecorresponding to Jan 1, year 0, 15:04:00 UTC (note that because the year is0, this time is before the zero Time).Years must be in the range 0000..9999. The day of the week is checkedfor syntax but it is otherwise ignored.
For layouts specifying the two-digit year 06, a value NN >= 69 will be treatedas 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 correspondsto a time zone used by the current location (Local), then Parse uses thatlocation and zone in the returned time. Otherwise it records the time asbeing 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 abbreviationhas 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 beingin 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 thesame layout losslessly, but the exact instant used in the representation willdiffer by the actual zone offset. To avoid such problems, prefer time layoutsthat use a numeric zone offset, or useParseInLocation.
Example¶
package mainimport ("fmt""time")func main() {// See the example for Time.Format for a thorough description of how// to define the layout string to parse a time.Time value; Parse and// Format use the same model to describe their input and output.// longForm shows by example how the reference time would be represented in// the desired layout.const longForm = "Jan 2, 2006 at 3:04pm (MST)"t, _ := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)")fmt.Println(t)// shortForm is another way the reference time would be represented// in the desired layout; it has no time zone present.// Note: without explicit zone, returns time in UTC.const shortForm = "2006-Jan-02"t, _ = time.Parse(shortForm, "2013-Feb-03")fmt.Println(t)// Some valid layouts are invalid time values, due to format specifiers// such as _ for space padding and Z for zone information.// For example the RFC3339 layout 2006-01-02T15:04:05Z07:00// contains both Z and a time zone offset in order to handle both valid options:// 2006-01-02T15:04:05Z// 2006-01-02T15:04:05+07:00t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")fmt.Println(t)t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05+07:00")fmt.Println(t)_, err := time.Parse(time.RFC3339, time.RFC3339)fmt.Println("error", err) // Returns an error as the layout is not a valid time value}
Output:2013-02-03 19:54:00 -0800 PST2013-02-03 00:00:00 +0000 UTC2006-01-02 15:04:05 +0000 UTC2006-01-02 15:04:05 +0700 +0700error parsing time "2006-01-02T15:04:05Z07:00": extra text: "07:00"
funcParseInLocation¶added ingo1.1
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 itagainst the Local location; ParseInLocation uses the given location.
Example¶
package mainimport ("fmt""time")func main() {loc, _ := time.LoadLocation("Europe/Berlin")// This will look for the name CEST in the Europe/Berlin time zone.const longForm = "Jan 2, 2006 at 3:04pm (MST)"t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)fmt.Println(t)// Note: without explicit zone, returns time in given location.const shortForm = "2006-Jan-02"t, _ = time.ParseInLocation(shortForm, "2012-Jul-09", loc)fmt.Println(t)}
Output:2012-07-09 05:02:00 +0200 CEST2012-07-09 00:00:00 +0200 CEST
funcUnix¶
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 suchvalue is 1<<63-1 (the largest int64 value).
Example¶
package mainimport ("fmt""time")func main() {unixTime := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)fmt.Println(unixTime.Unix())t := time.Unix(unixTime.Unix(), 0).UTC()fmt.Println(t)}
Output:12578940002009-11-10 23:00:00 +0000 UTC
funcUnixMicro¶added ingo1.17
UnixMicro returns the local Time corresponding to the given Unix time,usec microseconds since January 1, 1970 UTC.
Example¶
package mainimport ("fmt""time")func main() {umt := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)fmt.Println(umt.UnixMicro())t := time.UnixMicro(umt.UnixMicro()).UTC()fmt.Println(t)}
Output:12578940000000002009-11-10 23:00:00 +0000 UTC
funcUnixMilli¶added ingo1.17
UnixMilli returns the local Time corresponding to the given Unix time,msec milliseconds since January 1, 1970 UTC.
Example¶
package mainimport ("fmt""time")func main() {umt := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)fmt.Println(umt.UnixMilli())t := time.UnixMilli(umt.UnixMilli()).UTC()fmt.Println(t)}
Output:12578940000002009-11-10 23:00:00 +0000 UTC
func (Time)Add¶
Add returns the time t+d.
Example¶
package mainimport ("fmt""time")func main() {start := time.Date(2009, 1, 1, 12, 0, 0, 0, time.UTC)afterTenSeconds := start.Add(time.Second * 10)afterTenMinutes := start.Add(time.Minute * 10)afterTenHours := start.Add(time.Hour * 10)afterTenDays := start.Add(time.Hour * 24 * 10)fmt.Printf("start = %v\n", start)fmt.Printf("start.Add(time.Second * 10) = %v\n", afterTenSeconds)fmt.Printf("start.Add(time.Minute * 10) = %v\n", afterTenMinutes)fmt.Printf("start.Add(time.Hour * 10) = %v\n", afterTenHours)fmt.Printf("start.Add(time.Hour * 24 * 10) = %v\n", afterTenDays)}
Output:start = 2009-01-01 12:00:00 +0000 UTCstart.Add(time.Second * 10) = 2009-01-01 12:00:10 +0000 UTCstart.Add(time.Minute * 10) = 2009-01-01 12:10:00 +0000 UTCstart.Add(time.Hour * 10) = 2009-01-01 22:00:00 +0000 UTCstart.Add(time.Hour * 24 * 10) = 2009-01-11 12:00:00 +0000 UTC
func (Time)AddDate¶
AddDate returns the time corresponding to adding thegiven number of years, months, and days to t.For example, AddDate(-1, 2, 3) applied to January 1, 2011returns March 4, 2010.
Note that dates are fundamentally coupled to timezones, and calendricalperiods like days don't have fixed durations. AddDate uses the Location ofthe Time value to determine these durations. That means that the sameAddDate arguments can produce a different shift in absolute time depending onthe base Time value and its Location. For example, AddDate(0, 0, 1) appliedto 12:00 on March 27 always returns 12:00 on March 28. At some locations andin some years this is a 24 hour shift. In others it's a 23 hour shift due todaylight savings time transitions.
AddDate normalizes its result in the same way that Date does,so, for example, adding one month to October 31 yieldsDecember 1, the normalized form for November 31.
Example¶
package mainimport ("fmt""time")func main() {start := time.Date(2023, 03, 25, 12, 0, 0, 0, time.UTC)oneDayLater := start.AddDate(0, 0, 1)dayDuration := oneDayLater.Sub(start)oneMonthLater := start.AddDate(0, 1, 0)oneYearLater := start.AddDate(1, 0, 0)zurich, err := time.LoadLocation("Europe/Zurich")if err != nil {panic(err)}// This was the day before a daylight saving time transition in Zürich.startZurich := time.Date(2023, 03, 25, 12, 0, 0, 0, zurich)oneDayLaterZurich := startZurich.AddDate(0, 0, 1)dayDurationZurich := oneDayLaterZurich.Sub(startZurich)fmt.Printf("oneDayLater: start.AddDate(0, 0, 1) = %v\n", oneDayLater)fmt.Printf("oneMonthLater: start.AddDate(0, 1, 0) = %v\n", oneMonthLater)fmt.Printf("oneYearLater: start.AddDate(1, 0, 0) = %v\n", oneYearLater)fmt.Printf("oneDayLaterZurich: startZurich.AddDate(0, 0, 1) = %v\n", oneDayLaterZurich)fmt.Printf("Day duration in UTC: %v | Day duration in Zürich: %v\n", dayDuration, dayDurationZurich)}
Output:oneDayLater: start.AddDate(0, 0, 1) = 2023-03-26 12:00:00 +0000 UTConeMonthLater: start.AddDate(0, 1, 0) = 2023-04-25 12:00:00 +0000 UTConeYearLater: start.AddDate(1, 0, 0) = 2024-03-25 12:00:00 +0000 UTConeDayLaterZurich: startZurich.AddDate(0, 0, 1) = 2023-03-26 12:00:00 +0200 CESTDay duration in UTC: 24h0m0s | Day duration in Zürich: 23h0m0s
func (Time)After¶
After reports whether the time instant t is after u.
Example¶
package mainimport ("fmt""time")func main() {year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)isYear3000AfterYear2000 := year3000.After(year2000) // TrueisYear2000AfterYear3000 := year2000.After(year3000) // Falsefmt.Printf("year3000.After(year2000) = %v\n", isYear3000AfterYear2000)fmt.Printf("year2000.After(year3000) = %v\n", isYear2000AfterYear3000)}
Output:year3000.After(year2000) = trueyear2000.After(year3000) = false
func (Time)AppendBinary¶added ingo1.24.0
AppendBinary implements theencoding.BinaryAppender interface.
Example¶
package mainimport ("fmt""time")func main() {t := time.Date(2025, 4, 1, 15, 30, 45, 123456789, time.UTC)var buffer []bytebuffer, err := t.AppendBinary(buffer)if err != nil {panic(err)}var parseTime time.Timeerr = parseTime.UnmarshalBinary(buffer[:])if err != nil {panic(err)}fmt.Printf("t: %v\n", t)fmt.Printf("parseTime: %v\n", parseTime)fmt.Printf("equal: %v\n", parseTime.Equal(t))}
Output:t: 2025-04-01 15:30:45.123456789 +0000 UTCparseTime: 2025-04-01 15:30:45.123456789 +0000 UTCequal: true
func (Time)AppendFormat¶added ingo1.5
AppendFormat is likeTime.Format but appends the textualrepresentation to b and returns the extended buffer.
Example¶
package mainimport ("fmt""time")func main() {t := time.Date(2017, time.November, 4, 11, 0, 0, 0, time.UTC)text := []byte("Time: ")text = t.AppendFormat(text, time.Kitchen)fmt.Println(string(text))}
Output:Time: 11:00AM
func (Time)AppendText¶added ingo1.24.0
AppendText implements theencoding.TextAppender interface.The time is formatted inRFC 3339 format with sub-second precision.If the timestamp cannot be represented as validRFC 3339(e.g., the year is out of range), then an error is returned.
Example¶
package mainimport ("fmt""time")func main() {t := time.Date(2025, 4, 1, 15, 30, 45, 123456789, time.UTC)buffer := []byte("t: ")buffer, err := t.AppendText(buffer)if err != nil {panic(err)}fmt.Printf("%s\n", buffer)}
Output:t: 2025-04-01T15:30:45.123456789Z
func (Time)Before¶
Before reports whether the time instant t is before u.
Example¶
package mainimport ("fmt""time")func main() {year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)isYear2000BeforeYear3000 := year2000.Before(year3000) // TrueisYear3000BeforeYear2000 := year3000.Before(year2000) // Falsefmt.Printf("year2000.Before(year3000) = %v\n", isYear2000BeforeYear3000)fmt.Printf("year3000.Before(year2000) = %v\n", isYear3000BeforeYear2000)}
Output:year2000.Before(year3000) = trueyear3000.Before(year2000) = false
func (Time)Compare¶added ingo1.20
Compare compares the time instant t with u. If t is before u, it returns -1;if t is after u, it returns +1; if they're the same, it returns 0.
func (Time)Date¶
Date returns the year, month, and day in which t occurs.
Example¶
package mainimport ("fmt""time")func main() {d := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)year, month, day := d.Date()fmt.Printf("year = %v\n", year)fmt.Printf("month = %v\n", month)fmt.Printf("day = %v\n", day)}
Output:year = 2000month = Februaryday = 1
func (Time)Day¶
Day returns the day of the month specified by t.
Example¶
package mainimport ("fmt""time")func main() {d := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)day := d.Day()fmt.Printf("day = %v\n", day)}
Output:day = 1
func (Time)Equal¶
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 == withTime values; most code should use Equal instead.
Example¶
package mainimport ("fmt""time")func main() {secondsEastOfUTC := int((8 * time.Hour).Seconds())beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)// Unlike the equal operator, Equal is aware that d1 and d2 are the// same instant but in different time zones.d1 := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)d2 := time.Date(2000, 2, 1, 20, 30, 0, 0, beijing)datesEqualUsingEqualOperator := d1 == d2datesEqualUsingFunction := d1.Equal(d2)fmt.Printf("datesEqualUsingEqualOperator = %v\n", datesEqualUsingEqualOperator)fmt.Printf("datesEqualUsingFunction = %v\n", datesEqualUsingFunction)}
Output:datesEqualUsingEqualOperator = falsedatesEqualUsingFunction = true
func (Time)Format¶
Format returns a textual representation of the time value formatted accordingto the layout defined by the argument. See the documentation for theconstant calledLayout to see how to represent the layout format.
The executable example forTime.Format demonstrates the workingof the layout string in detail and is a good reference.
Example¶
package mainimport ("fmt""time")func main() {// Parse a time value from a string in the standard Unix format.t, err := time.Parse(time.UnixDate, "Wed Feb 25 11:06:39 PST 2015")if err != nil { // Always check errors even if they should not happen.panic(err)}tz, err := time.LoadLocation("Asia/Shanghai")if err != nil { // Always check errors even if they should not happen.panic(err)}// time.Time's Stringer method is useful without any format.fmt.Println("default format:", t)// Predefined constants in the package implement common layouts.fmt.Println("Unix format:", t.Format(time.UnixDate))// The time zone attached to the time value affects its output.fmt.Println("Same, in UTC:", t.UTC().Format(time.UnixDate))fmt.Println("in Shanghai with seconds:", t.In(tz).Format("2006-01-02T15:04:05 -070000"))fmt.Println("in Shanghai with colon seconds:", t.In(tz).Format("2006-01-02T15:04:05 -07:00:00"))// The rest of this function demonstrates the properties of the// layout string used in the format.// The layout string used by the Parse function and Format method// shows by example how the reference time should be represented.// We stress that one must show how the reference time is formatted,// not a time of the user's choosing. Thus each layout string is a// representation of the time stamp,//Jan 2 15:04:05 2006 MST// An easy way to remember this value is that it holds, when presented// in this order, the values (lined up with the elements above):// 1 2 3 4 5 6 -7// There are some wrinkles illustrated below.// Most uses of Format and Parse use constant layout strings such as// the ones defined in this package, but the interface is flexible,// as these examples show.// Define a helper function to make the examples' output look nice.do := func(name, layout, want string) {got := t.Format(layout)if want != got {fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)return}fmt.Printf("%-16s %q gives %q\n", name, layout, got)}// Print a header in our output.fmt.Printf("\nFormats:\n\n")// Simple starter examples.do("Basic full date", "Mon Jan 2 15:04:05 MST 2006", "Wed Feb 25 11:06:39 PST 2015")do("Basic short date", "2006/01/02", "2015/02/25")// The hour of the reference time is 15, or 3PM. The layout can express// it either way, and since our value is the morning we should see it as// an AM time. We show both in one format string. Lower case too.do("AM/PM", "3PM==3pm==15h", "11AM==11am==11h")// When parsing, if the seconds value is followed by a decimal point// and some digits, that is taken as a fraction of a second even if// the layout string does not represent the fractional second.// Here we add a fractional second to our time value used above.t, err = time.Parse(time.UnixDate, "Wed Feb 25 11:06:39.1234 PST 2015")if err != nil {panic(err)}// It does not appear in the output if the layout string does not contain// a representation of the fractional second.do("No fraction", time.UnixDate, "Wed Feb 25 11:06:39 PST 2015")// Fractional seconds can be printed by adding a run of 0s or 9s after// a decimal point in the seconds value in the layout string.// If the layout digits are 0s, the fractional second is of the specified// width. Note that the output has a trailing zero.do("0s for fraction", "15:04:05.00000", "11:06:39.12340")// If the fraction in the layout is 9s, trailing zeros are dropped.do("9s for fraction", "15:04:05.99999999", "11:06:39.1234")}
Output:default format: 2015-02-25 11:06:39 -0800 PSTUnix format: Wed Feb 25 11:06:39 PST 2015Same, in UTC: Wed Feb 25 19:06:39 UTC 2015in Shanghai with seconds: 2015-02-26T03:06:39 +080000in Shanghai with colon seconds: 2015-02-26T03:06:39 +08:00:00Formats: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"
Example (Pad)¶
package mainimport ("fmt""time")func main() {// Parse a time value from a string in the standard Unix format.t, err := time.Parse(time.UnixDate, "Sat Mar 7 11:06:39 PST 2015")if err != nil { // Always check errors even if they should not happen.panic(err)}// Define a helper function to make the examples' output look nice.do := func(name, layout, want string) {got := t.Format(layout)if want != got {fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)return}fmt.Printf("%-16s %q gives %q\n", name, layout, got)}// The predefined constant Unix uses an underscore to pad the day.do("Unix", time.UnixDate, "Sat Mar 7 11:06:39 PST 2015")// For fixed-width printing of values, such as the date, that may be one or// two characters (7 vs. 07), use an _ instead of a space in the layout string.// Here we print just the day, which is 2 in our layout string and 7 in our// value.do("No pad", "<2>", "<7>")// An underscore represents a space pad, if the date only has one digit.do("Spaces", "<_2>", "< 7>")// A "0" indicates zero padding for single-digit values.do("Zeros", "<02>", "<07>")// If the value is already the right width, padding is not used.// For instance, the second (05 in the reference time) in our value is 39,// so it doesn't need padding, but the minutes (04, 06) does.do("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 (Time)GoString¶added ingo1.17
GoString implementsfmt.GoStringer and formats t to be printed in Go sourcecode.
Example¶
package mainimport ("fmt""time")func main() {t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)fmt.Println(t.GoString())t = t.Add(1 * time.Minute)fmt.Println(t.GoString())t = t.AddDate(0, 1, 0)fmt.Println(t.GoString())t, _ = time.Parse("Jan 2, 2006 at 3:04pm (MST)", "Feb 3, 2013 at 7:54pm (UTC)")fmt.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 (Time)ISOWeek¶
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 toweek 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1of year n+1.
func (Time)In¶
In returns a copy of t representing the same time instant, butwith the copy's location information set to loc for displaypurposes.
In panics if loc is nil.
func (Time)IsDST¶added ingo1.17
IsDST reports whether the time in the configured location is in Daylight Savings Time.
func (Time)IsZero¶
IsZero reports whether t represents the zero time instant,January 1, year 1, 00:00:00 UTC.
func (Time)MarshalBinary¶added ingo1.2
MarshalBinary implements theencoding.BinaryMarshaler interface.
func (Time)MarshalJSON¶
MarshalJSON implements theencoding/json.Marshaler interface.The time is a quoted string in theRFC 3339 format with sub-second precision.If the timestamp cannot be represented as validRFC 3339(e.g., the year is out of range), then an error is reported.
func (Time)MarshalText¶added ingo1.2
MarshalText implements theencoding.TextMarshaler interface. The outputmatches that of calling theTime.AppendText method.
SeeTime.AppendText for more information.
func (Time)Minute¶
Minute returns the minute offset within the hour specified by t, in the range [0, 59].
func (Time)Nanosecond¶
Nanosecond returns the nanosecond offset within the second specified by t,in the range [0, 999999999].
func (Time)Round¶added ingo1.1
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 thezero time; it does not operate on the presentation form of thetime. Thus, Round(Hour) may return a time with a non-zerominute, depending on the time's Location.
Example¶
package mainimport ("fmt""time")func main() {t := time.Date(0, 0, 0, 12, 15, 30, 918273645, time.UTC)round := []time.Duration{time.Nanosecond,time.Microsecond,time.Millisecond,time.Second,2 * time.Second,time.Minute,10 * time.Minute,time.Hour,}for _, d := range round {fmt.Printf("t.Round(%6s) = %s\n", d, t.Round(d).Format("15:04:05.999999999"))}}
Output:t.Round( 1ns) = 12:15:30.918273645t.Round( 1µs) = 12:15:30.918274t.Round( 1ms) = 12:15:30.918t.Round( 1s) = 12:15:31t.Round( 2s) = 12:15:30t.Round( 1m0s) = 12:16:00t.Round( 10m0s) = 12:20:00t.Round(1h0m0s) = 12:00:00
func (Time)Second¶
Second returns the second offset within the minute specified by t, in the range [0, 59].
func (Time)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 stringincludes a final field "m=±<value>", where value is the monotonicclock reading formatted as a decimal number of seconds.
The returned string is meant for debugging; for a stable serializedrepresentation, use t.MarshalText, t.MarshalBinary, or t.Formatwith an explicit format string.
Example¶
package mainimport ("fmt""time")func main() {timeWithNanoseconds := time.Date(2000, 2, 1, 12, 13, 14, 15, time.UTC)withNanoseconds := timeWithNanoseconds.String()timeWithoutNanoseconds := time.Date(2000, 2, 1, 12, 13, 14, 0, time.UTC)withoutNanoseconds := timeWithoutNanoseconds.String()fmt.Printf("withNanoseconds = %v\n", string(withNanoseconds))fmt.Printf("withoutNanoseconds = %v\n", string(withoutNanoseconds))}
Output:withNanoseconds = 2000-02-01 12:13:14.000000015 +0000 UTCwithoutNanoseconds = 2000-02-01 12:13:14 +0000 UTC
func (Time)Sub¶
Sub returns the duration t-u. If the result exceeds the maximum (or minimum)value that can be stored in aDuration, the maximum (or minimum) durationwill be returned.To compute t-d for a duration d, use t.Add(-d).
Example¶
package mainimport ("fmt""time")func main() {start := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)end := time.Date(2000, 1, 1, 12, 0, 0, 0, time.UTC)difference := end.Sub(start)fmt.Printf("difference = %v\n", difference)}
Output:difference = 12h0m0s
func (Time)Truncate¶added ingo1.1
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 thezero time; it does not operate on the presentation form of thetime. Thus, Truncate(Hour) may return a time with a non-zerominute, depending on the time's Location.
Example¶
package mainimport ("fmt""time")func main() {t, _ := time.Parse("2006 Jan 02 15:04:05", "2012 Dec 07 12:15:30.918273645")trunc := []time.Duration{time.Nanosecond,time.Microsecond,time.Millisecond,time.Second,2 * time.Second,time.Minute,10 * time.Minute,}for _, d := range trunc {fmt.Printf("t.Truncate(%5s) = %s\n", d, t.Truncate(d).Format("15:04:05.999999999"))}// To round to the last midnight in the local timezone, create a new Date.midnight := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)_ = midnight}
Output:t.Truncate( 1ns) = 12:15:30.918273645t.Truncate( 1µs) = 12:15:30.918273t.Truncate( 1ms) = 12:15:30.918t.Truncate( 1s) = 12:15:30t.Truncate( 2s) = 12:15:30t.Truncate( 1m0s) = 12:15:00t.Truncate(10m0s) = 12:10:00
func (Time)Unix¶
Unix returns t as a Unix time, the number of seconds elapsedsince January 1, 1970 UTC. The result does not depend on thelocation associated with t.Unix-like operating systems often record time as a 32-bitcount of seconds, but since the method here returns a 64-bitvalue it is valid for billions of years into the past or future.
Example¶
package mainimport ("fmt""time")func main() {// 1 billion seconds of Unix, three ways.fmt.Println(time.Unix(1e9, 0).UTC()) // 1e9 secondsfmt.Println(time.Unix(0, 1e18).UTC()) // 1e18 nanosecondsfmt.Println(time.Unix(2e9, -1e18).UTC()) // 2e9 seconds - 1e18 nanosecondst := time.Date(2001, time.September, 9, 1, 46, 40, 0, time.UTC)fmt.Println(t.Unix()) // seconds since 1970fmt.Println(t.UnixNano()) // nanoseconds since 1970}
Output:2001-09-09 01:46:40 +0000 UTC2001-09-09 01:46:40 +0000 UTC2001-09-09 01:46:40 +0000 UTC10000000001000000000000000000
func (Time)UnixMicro¶added ingo1.17
UnixMicro returns t as a Unix time, the number of microseconds elapsed sinceJanuary 1, 1970 UTC. The result is undefined if the Unix time inmicroseconds cannot be represented by an int64 (a date before year -290307 orafter year 294246). The result does not depend on the location associatedwith t.
func (Time)UnixMilli¶added ingo1.17
UnixMilli returns t as a Unix time, the number of milliseconds elapsed sinceJanuary 1, 1970 UTC. The result is undefined if the Unix time inmilliseconds cannot be represented by an int64 (a date more than 292 millionyears before or after 1970). The result does not depend on thelocation associated with t.
func (Time)UnixNano¶
UnixNano returns t as a Unix time, the number of nanoseconds elapsedsince January 1, 1970 UTC. The result is undefined if the Unix timein nanoseconds cannot be represented by an int64 (a date before the year1678 or after 2262). Note that this means the result of calling UnixNanoon the zero Time is undefined. The result does not depend on thelocation associated with t.
func (*Time)UnmarshalBinary¶added ingo1.2
UnmarshalBinary implements theencoding.BinaryUnmarshaler interface.
func (*Time)UnmarshalJSON¶
UnmarshalJSON implements theencoding/json.Unmarshaler interface.The time must be a quoted string in theRFC 3339 format.
func (*Time)UnmarshalText¶added ingo1.2
UnmarshalText implements theencoding.TextUnmarshaler interface.The time must be in theRFC 3339 format.
func (Time)YearDay¶added ingo1.1
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¶
Zone computes the time zone in effect at time t, returning the abbreviatedname of the zone (such as "CET") and its offset in seconds east of UTC.
func (Time)ZoneBounds¶added ingo1.19
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.
typeTimer¶
type Timer struct {C <-chanTime// 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 byAfterFunc.A Timer must be created withNewTimer or AfterFunc.
funcAfterFunc¶
AfterFunc waits for the duration to elapse and then calls fin its own goroutine. It returns aTimer that canbe used to cancel the call using its Stop method.The returned Timer's C field is not used and will be nil.
funcNewTimer¶
NewTimer creates a new Timer that will sendthe current time on its channel after at least duration d.
Before Go 1.23, the garbage collector did not recovertimers that had not yet expired or been stopped, so code oftenimmediately deferred t.Stop after calling NewTimer, to makethe timer recoverable when it was no longer needed.As of Go 1.23, the garbage collector can recover unreferencedtimers, even if they haven't expired or been stopped.The Stop method is no longer necessary to help the garbage collector.(Code may of course still want to call Stop to stop the timer for other reasons.)
Before Go 1.23, the channel associated with a Timer wasasynchronous (buffered, capacity 1), which meant thatstale time values could be received even afterTimer.StoporTimer.Reset returned.As of Go 1.23, the channel is synchronous (unbuffered, capacity 0),eliminating the possibility of those stale values.
The GODEBUG setting asynctimerchan=1 restores both pre-Go 1.23behaviors: when set, unexpired timers won't be garbage collected, andchannels will have buffered capacity. This setting may be removedin Go 1.27 or later.
func (*Timer)Reset¶added ingo1.1
Reset changes the timer to expire after duration d.It returns true if the timer had been active, false if the timer hadexpired or been stopped.
For a func-based timer created withAfterFunc(d, f), Reset either rescheduleswhen f will run, in which case Reset returns true, or schedules fto run again, in which case it returns false.When Reset returns false, Reset neither waits for the prior f tocomplete before returning nor does it guarantee that the subsequentgoroutine running f does not run concurrently with the priorone. If the caller needs to know whether the prior execution off is completed, it must coordinate with f explicitly.
For a chan-based timer created with NewTimer, as of Go 1.23,any receive from t.C after Reset has returned is guaranteed notto receive a time value corresponding to the previous timer settings;if the program has not received from t.C already and the timer isrunning, Reset is guaranteed to return true.Before Go 1.23, the only safe way to use Reset was to callTimer.Stopand explicitly drain the timer first.See theNewTimer documentation for more details.
func (*Timer)Stop¶
Stop prevents theTimer from firing.It returns true if the call stops the timer, false if the timer has alreadyexpired or been stopped.
For a func-based timer created withAfterFunc(d, f),if t.Stop returns false, then the timer has already expiredand 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.
For a chan-based timer created with NewTimer(d), as of Go 1.23,any receive from t.C after Stop has returned is guaranteed to blockrather than receive a stale time value from before the Stop;if the program has not received from t.C already and the timer isrunning, Stop is guaranteed to return true.Before Go 1.23, the only safe way to use Stop was insert an extra<-t.C if Stop returned false to drain a potential stale value.See theNewTimer documentation for more details.