Documentation ¶
Overview ¶
Package time provides functionality for measuring and displaying time.
The calendrical calculations always assume a Gregorian calendar.
Index ¶
- Constants
- func After(d Duration) <-chan Time
- func Sleep(d Duration)
- func Tick(d Duration) <-chan Time
- type Duration
- type Location
- type Month
- type ParseError
- type Ticker
- type 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) Date() (year int, month Month, day int)
- func (t Time) Day() int
- func (t Time) Equal(u Time) bool
- func (t Time) Format(layout string) string
- func (t *Time) GobDecode(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) 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) 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)
- type Timer
- type Weekday
Examples ¶
Constants ¶
const ( ANSIC = "Mon Jan _2 15:04:05 2006" UnixDate = "Mon Jan _2 15:04:05 MST 2006" RubyDate = "Mon Jan 02 15:04:05 -0700 2006" RFC822 = "02 Jan 06 15:04 MST" RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone RFC850 = "Monday, 02-Jan-06 15:04:05 MST" RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST" RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone RFC3339 = "2006-01-02T15:04:05Z07:00" RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00" Kitchen = "3:04PM" // Handy time stamps. Stamp = "Jan _2 15:04:05" StampMilli = "Jan _2 15:04:05.000" StampMicro = "Jan _2 15:04:05.000000" StampNano = "Jan _2 15:04:05.000000000" )
These are predefined layouts for use in Time.Format and Time.Parse. The reference time used in the layouts is the specific time:
Mon Jan 2 15:04:05 MST 2006
which is Unix time 1136239445. Since MST is GMT-0700, the reference time can be thought of as
01/02 03:04:05PM '06 -0700
To define your own format, write down what the reference time would look like formatted your way; see the values of constants like ANSIC, StampMicro or Kitchen for examples. The model is to demonstrate what the reference time looks like so that the Format and Parse methods can apply the same transformation to a general time value.
Within the format string, an underscore _ represents a space that may be replaced by a digit if the following number (a day) has two digits; for compatibility with fixed-width Unix time formats.
A decimal point followed by one or more zeros represents a fractional second, printed to the given number of decimal places. A decimal point followed by one or more nines represents a fractional second, printed to the given number of decimal places, with trailing zeros removed. When parsing (only), the input may contain a fractional second field immediately after the seconds field, even if the layout does not signify its presence. In that case a decimal point followed by a maximal series of digits is parsed as a fractional second.
Numeric time zone offsets format as follows:
-0700 ±hhmm -07:00 ±hh:mm -07 ±hh
Replacing the sign in the format with a Z triggers the ISO 8601 behavior of printing Z instead of an offset for the UTC zone. Thus:
Z0700 Z or ±hhmm Z07:00 Z or ±hh:mm Z07 Z or ±hh
The executable example for time.Format demonstrates the working of the layout string in detail and is a good reference.
Note that the RFC822, RFC850, and RFC1123 formats should be applied only to local times. Applying them to UTC times will use "UTC" as the time zone abbreviation, while strictly speaking those RFCs require the use of "GMT" in that case. In general RFC1123Z should be used instead of RFC1123 for servers that insist on that format, and RFC3339 should be preferred for new protocols. RFC822, RFC822Z, RFC1123, and RFC1123Z are useful for formatting; when used with time.Parse they do not accept all the time formats permitted by the RFCs.
const ( Nanosecond Duration = 1 Microsecond = 1000 * Nanosecond Millisecond = 1000 * Microsecond Second = 1000 * Millisecond Minute = 60 * Second Hour = 60 * Minute )
Common durations. There is no definition for units of Day or larger to avoid confusion across daylight savings time zone transitions.
To count the number of units in a Duration, divide:
second := time.Second fmt.Print(int64(second/time.Millisecond)) // prints 1000
To convert an integer number of units to a Duration, multiply:
seconds := 10 fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
Variables ¶
This section is empty.
Functions ¶
func After ¶
After waits for the duration to elapse and then sends the current time on the returned channel. It is equivalent to NewTimer(d).C. The underlying Timer is not recovered by the garbage collector until the timer fires. If efficiency is a concern, use NewTimer instead and call Timer.Stop if the timer is no longer needed.
Example ¶
package main import ( "fmt" "time" ) var c chan int func handle(int) {} func main() { select { case m := <-c: handle(m) case <-time.After(5 * time.Minute): fmt.Println("timed out") } }
Output:
func Sleep ¶
func Sleep(d Duration)
Sleep pauses the current goroutine for at least the duration d. A negative or zero duration causes Sleep to return immediately.
func Tick ¶
Tick is a convenience wrapper for NewTicker providing access to the ticking channel only. While Tick is useful for clients that have no need to shut down the Ticker, be aware that without a way to shut it down the underlying Ticker cannot be recovered by the garbage collector; it "leaks". Unlike NewTicker, Tick will return nil if d <= 0.
Example ¶
package main import ( "fmt" "time" ) func statusUpdate() string { return "" } func main() { c := time.Tick(1 * time.Minute) for now := range c { fmt.Printf("%v %s\n", now, statusUpdate()) } }
Output:
Types ¶
type Duration ¶
type Duration int64
A Duration represents the elapsed time between two instants as an int64 nanosecond count. The representation limits the largest representable duration to approximately 290 years.
Example ¶
package main import ( "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)) }
Output:
func ParseDuration ¶
ParseDuration parses a duration string. A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
func (Duration) Nanoseconds ¶
Nanoseconds returns the duration as an integer nanosecond count.
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 one second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure that the leading digit is non-zero. The zero duration formats as 0, with no unit.
type Location ¶
type Location struct {
// contains filtered or unexported fields
}
A Location maps time instants to the zone in use at that time. Typically, the Location represents the collection of time offsets in use in a geographical area, such as CEST and CET for central Europe.
var Local *Location = &localLoc
Local represents the system's local time zone.
var UTC *Location = &utcLoc
UTC represents Universal Coordinated Time (UTC).
func FixedZone ¶
FixedZone returns a Location that always uses the given zone name and offset (seconds east of UTC).
func LoadLocation ¶
LoadLocation returns the Location with the given name.
If the name is "" or "UTC", LoadLocation returns UTC. If the name is "Local", LoadLocation returns Local.
Otherwise, the name is taken to be a location name corresponding to a file in the IANA Time Zone database, such as "America/New_York".
The time zone database needed by LoadLocation may not be present on all systems, especially non-Unix systems. LoadLocation looks in the directory or uncompressed zip file named by the ZONEINFO environment variable, if any, then looks in known installation locations on Unix systems, and finally looks in $GOROOT/lib/time/zoneinfo.zip.
type Month ¶
type Month int
A Month specifies a month of the year (January = 1, ...).
Example ¶
package main import ( "fmt" "time" ) func main() { _, month, day := time.Now().Date() if month == time.November && day == 10 { fmt.Println("Happy Go day!") } }
Output:
type ParseError ¶
type ParseError struct { Layout string Value string LayoutElem string ValueElem string Message string }
ParseError describes a problem parsing a time string.
func (*ParseError) Error ¶
func (e *ParseError) Error() string
Error returns the string representation of a ParseError.
type Ticker ¶
type Ticker struct { C <-chan Time // The channel on which the ticks are delivered. // contains filtered or unexported fields }
A Ticker holds a channel that delivers `ticks' of a clock at intervals.
func NewTicker ¶
NewTicker returns a new Ticker containing a channel that will send the time with a period specified by the duration argument. It adjusts the intervals or drops ticks to make up for slow receivers. The duration d must be greater than zero; if not, NewTicker will panic. Stop the ticker to release associated resources.
type Time ¶
type Time struct {
// contains filtered or unexported fields
}
A Time represents an instant in time with nanosecond precision.
Programs using times should typically store and pass them as values, not pointers. That is, time variables and struct fields should be of type time.Time, not *time.Time. A Time value can be used by multiple goroutines simultaneously.
Time instants can be compared using the Before, After, and Equal methods. The Sub method subtracts two instants, producing a Duration. The Add method adds a Time and a Duration, producing a Time.
The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC. As this time is unlikely to come up in practice, the IsZero method gives a simple way of detecting a time that has not been initialized explicitly.
Each Time has associated with it a Location, consulted when computing the presentation form of the time, such as in the Format, Hour, and Year methods. The methods Local, UTC, and In return a Time with a specific location. Changing the location in this way changes only the presentation; it does not change the instant in time being denoted and therefore does not affect the computations described in earlier paragraphs.
Note that the Go == operator compares not just the time instant but also the Location. 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.
func Date ¶
Date returns the Time corresponding to
yyyy-mm-dd hh:mm:ss + nsec nanoseconds
in the appropriate zone for that time in the given location.
The month, day, hour, min, sec, and nsec values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 1.
A daylight savings time transition skips or repeats times. For example, in the United States, March 13, 2011 2:15am never occurred, while November 6, 2011 1:15am occurred twice. In such cases, the choice of time zone, and therefore the time, is not well-defined. Date returns a time that is correct in one of the two zones involved in the transition, but it does not guarantee which.
Date panics if loc is nil.
Example ¶
package main import ( "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
func Parse ¶
Parse parses a formatted string and returns the time value it represents. The layout defines the format by showing how the reference time, defined to be
Mon Jan 2 15:04:05 -0700 MST 2006
would be interpreted if it were the value; it serves as an example of the input format. The same interpretation will then be made to the input string.
Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard and convenient representations of the reference time. For more information about the formats and the definition of the reference time, see the documentation for ANSIC and the other constants defined by this package. Also, the executable example for time.Format demonstrates the working of the layout string in detail and is a good reference.
Elements omitted from the value are assumed to be zero or, when zero is impossible, one, so parsing "3:04pm" returns the time corresponding to Jan 1, year 0, 15:04:00 UTC (note that because the year is 0, this time is before the zero Time). Years must be in the range 0000..9999. The day of the week is checked for syntax but it is otherwise ignored.
In the absence of a time zone indicator, Parse returns a time in UTC.
When parsing a time with a zone offset like -0700, if the offset corresponds to a time zone used by the current location (Local), then Parse uses that location and zone in the returned time. Otherwise it records the time as being in a fabricated location with time fixed at the given zone offset.
No checking is done that the day of the month is within the month's valid dates; any one- or two-digit value is accepted. For example February 31 and even February 99 are valid dates, specifying dates in March and May. This behavior is consistent with time.Date.
When parsing a time with a zone abbreviation like MST, if the zone abbreviation has a defined offset in the current location, then that offset is used. The zone abbreviation "UTC" is recognized as UTC regardless of location. If the zone abbreviation is unknown, Parse records the time as being in a fabricated location with the given zone abbreviation and a zero offset. This choice means that such a time can be parsed and reformatted with the same layout losslessly, but the exact instant used in the representation will differ by the actual zone offset. To avoid such problems, prefer time layouts that use a numeric zone offset, or use ParseInLocation.
Example ¶
package main import ( "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) }
Output: 2013-02-03 19:54:00 -0800 PST 2013-02-03 00:00:00 +0000 UTC
func ParseInLocation ¶
ParseInLocation is like Parse but differs in two important ways. First, in the absence of time zone information, Parse interprets a time as UTC; ParseInLocation interprets the time as in the given location. Second, when given a zone offset or abbreviation, Parse tries to match it against the Local location; ParseInLocation uses the given location.
Example ¶
package main import ( "fmt" "time" ) func main() { loc, _ := time.LoadLocation("Europe/Berlin") 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 CEST 2012-07-09 00:00:00 +0200 CEST
func Unix ¶
Unix returns the local Time corresponding to the given Unix time, sec seconds and nsec nanoseconds since January 1, 1970 UTC. It is valid to pass nsec outside the range [0, 999999999]. Not all sec values have a corresponding time value. One such value is 1<<63-1 (the largest int64 value).
func (Time) AddDate ¶
AddDate returns the time corresponding to adding the given number of years, months, and days to t. For example, AddDate(-1, 2, 3) applied to January 1, 2011 returns March 4, 2010.
AddDate normalizes its result in the same way that Date does, so, for example, adding one month to October 31 yields December 1, the normalized form for November 31.
func (Time) AppendFormat ¶
AppendFormat is like Format but appends the textual representation to b and returns the extended buffer.
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 CEST and 4:00 UTC are Equal. This comparison is different from using t == u, which also compares the locations.
func (Time) Format ¶
Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time, defined to be
Mon Jan 2 15:04:05 -0700 MST 2006
would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value.
A fractional second is represented by adding a period and zeros to the end of the seconds section of layout string, as in "15:04:05.000" to format a time stamp with millisecond precision.
Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard and convenient representations of the reference time. For more information about the formats and the definition of the reference time, see the documentation for ANSIC and the other constants defined by this package.
Example ¶
package main import ( "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) } // 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)) // 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("%-15s %q gives %q\n", name, layout, got) } // Print a header in our output. fmt.Printf("\nFormats:\n\n") // A simple starter example. do("Basic", "Mon Jan 2 15:04:05 MST 2006", "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 zero pad, if required. do("Spaces", "<_2>", "< 7>") // Similarly, a 0 indicates zero padding. 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") // The predefined constant Unix uses an underscore to pad the day. // Compare with our simple starter example. do("Unix", time.UnixDate, "Sat Mar 7 11:06:39 PST 2015") // 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, "Sat Mar 7 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, "Sat Mar 7 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-03-07 11:06:39 -0800 PST Unix format: Sat Mar 7 11:06:39 PST 2015 Same, in UTC: Sat Mar 7 19:06:39 UTC 2015 Formats: Basic "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" Unix "Mon Jan _2 15:04:05 MST 2006" gives "Sat Mar 7 11:06:39 PST 2015" AM/PM "3PM==3pm==15h" gives "11AM==11am==11h" No fraction "Mon Jan _2 15:04:05 MST 2006" gives "Sat Mar 7 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"
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 to week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 of year n+1.
func (Time) IsZero ¶
IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.
func (Time) MarshalBinary ¶
MarshalBinary implements the encoding.BinaryMarshaler interface.
func (Time) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface. The time is a quoted string in RFC 3339 format, with sub-second precision added if present.
func (Time) MarshalText ¶
MarshalText implements the encoding.TextMarshaler interface. The time is formatted in RFC 3339 format, with sub-second precision added if present.
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 ¶
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 unchanged.
Example ¶
package main import ( "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.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 (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"
func (Time) Sub ¶
Sub returns the duration t-u. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, the maximum (or minimum) duration will be returned. To compute t-d for a duration d, use t.Add(-d).
func (Time) Truncate ¶
Truncate returns the result of rounding t down to a multiple of d (since the zero time). If d <= 0, Truncate returns t unchanged.
Example ¶
package main import ( "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, time.Hour, } for _, d := range trunc { fmt.Printf("t.Truncate(%6s) = %s\n", d, t.Truncate(d).Format("15:04:05.999999999")) } }
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 t.Truncate(1h0m0s) = 12:00:00
func (Time) Unix ¶
Unix returns t as a Unix time, the number of seconds elapsed since January 1, 1970 UTC.
func (Time) UnixNano ¶
UnixNano returns t as a Unix time, the number of nanoseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in nanoseconds cannot be represented by an int64. Note that this means the result of calling UnixNano on the zero Time is undefined.
func (*Time) UnmarshalBinary ¶
UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
func (*Time) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface. The time is expected to be a quoted string in RFC 3339 format.
func (*Time) UnmarshalText ¶
UnmarshalText implements the encoding.TextUnmarshaler interface. The time is expected to be in RFC 3339 format.
type Timer ¶
type Timer struct { C <-chan Time // contains filtered or unexported fields }
The Timer type represents a single event. When the Timer expires, the current time will be sent on C, unless the Timer was created by AfterFunc. A Timer must be created with NewTimer or AfterFunc.
func AfterFunc ¶
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 ¶
NewTimer creates a new Timer that will send the current time on its channel after at least duration d.
func (*Timer) Reset ¶
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.
To reuse an active timer, always call its Stop method first and—if it had expired—drain the value from its channel. For example:
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 used in concert with Stop, as described above. The return value exists to preserve compatibility with existing programs.
func (*Timer) Stop ¶
Stop prevents the Timer from firing. It returns true if the call stops the timer, false if the timer has already expired or been stopped. Stop does not close the channel, to prevent a read from the channel succeeding incorrectly.
To prevent the timer firing after a call to Stop, check the return value and drain the channel. For example:
if !t.Stop() { <-t.C }
This cannot be done concurrent to other receives from the Timer's channel.