Documentation ¶
Index ¶
- Constants
- func After(d Duration) <-chan Time
- func Sleep(d Duration)
- 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 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) 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) Hour() int
- func (t Time) ISOWeek() (year, week int)
- func (t Time) IsZero() bool
- func (t Time) Local() Time
- func (t Time) Minute() int
- func (t Time) Month() Month
- func (t Time) Nanosecond() int
- func (t Time) Second() int
- func (t Time) String() string
- func (t Time) Sub(u Time) Duration
- func (t Time) UTC() Time
- func (t Time) Weekday() Weekday
- func (t Time) Year() int
- func (t Time) YearDay() int
- type Timer
- type Weekday
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 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" DateTime = "2006-01-02 15:04:05" DateOnly = "2006-01-02" TimeOnly = "15:04:05" )
These are predefined layouts for use in Time.Format and time.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 named Layout, listed below. As a Unix time, this is 1136239445. Since MST is GMT-0700, the reference would be printed 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 convention of putting the numerical month before the day.
The example for Time.Format demonstrates the working of the layout string in detail and is a good reference.
Note that the RFC822, RFC850, and RFC1123 formats should be applied only to local times. Applying them to UTC times will use "UTC" as the time zone abbreviation, while strictly speaking those RFCs require the use of "GMT" in that case. In general RFC1123Z should be used instead of RFC1123 for servers that insist on that format, and RFC3339 should be preferred for new protocols. RFC3339, RFC822, RFC822Z, RFC1123, and RFC1123Z are useful for formatting; when used with time.Parse they do not accept all the time formats permitted by the RFCs and they do accept time formats not formally defined. The RFC3339Nano format removes trailing zeros from the seconds field and thus may not sort correctly once formatted.
Most programs can use one of the defined constants as the layout passed to Format or Parse. The rest of this comment can be ignored unless you are creating a custom layout string.
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.
Here is a summary of the components of a layout string. Each element shows by example the formatting of an element of the reference time. Only these values are recognized. Text in the layout string that is not recognized as part of the reference time is echoed verbatim during Format and expected to appear verbatim in the input to Parse.
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 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 "Z070000" Z or ±hhmmss "Z07:00:00" Z or ±hh:mm:ss
Within the format string, the underscores in "_2" and "__2" represent spaces that may be replaced by digits if the following number has multiple digits, for compatibility with fixed-width Unix time formats. A leading zero represents a zero-padded value.
The formats __2 and 002 are space-padded and zero-padded three-character day of year; there is no unpadded day of year format.
A comma or decimal point followed by one or more zeros represents a fractional second, printed to the given number of decimal places. A comma or decimal point followed by one or more nines represents a fractional second, printed to the given number of decimal places, with trailing zeros removed. For example "15:04:05,000" or "15:04:05.000" formats or parses with millisecond precision.
Some valid layouts are invalid time values for time.Parse, due to formats such as _ for space padding and Z for zone information.
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 ¶ added in v0.9.1
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.
Types ¶
type Duration ¶ added in v0.9.1
type Duration int64
A Duration represents the elapsed time between two instants as an int64 nanosecond count. The representation limits the largest representable duration to approximately 290 years.
func ParseDuration ¶ added in v0.9.2
ParseDuration parses a duration string. A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
func Since ¶ added in v0.9.1
Since returns the time elapsed since t. It is shorthand for time.Now().Sub(t).
func Until ¶ added in v0.9.1
Until returns the duration until t. It is shorthand for t.Sub(time.Now()).
func (Duration) Abs ¶ added in v0.9.1
Abs returns the absolute value of d. As a special case, math.MinInt64 is converted to math.MaxInt64.
func (Duration) Hours ¶ added in v0.9.1
Hours returns the duration as a floating point number of hours.
func (Duration) Microseconds ¶ added in v0.9.1
Microseconds returns the duration as an integer microsecond count.
func (Duration) Milliseconds ¶ added in v0.9.1
Milliseconds returns the duration as an integer millisecond count.
func (Duration) Minutes ¶ added in v0.9.1
Minutes returns the duration as a floating point number of minutes.
func (Duration) Nanoseconds ¶ added in v0.9.1
Nanoseconds returns the duration as an integer nanosecond count.
func (Duration) Round ¶ added in v0.9.1
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.
func (Duration) Seconds ¶ added in v0.9.1
Seconds returns the duration as a floating point number of seconds.
func (Duration) String ¶ added in v0.9.1
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.
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. For many Locations the time offset varies depending on whether daylight savings time is in use at the time instant.
var Local *Location = &localLoc
Local represents the system's local time zone. On Unix systems, Local consults the TZ environment variable to find the time zone to use. No TZ means use 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).
func FixedZone ¶
FixedZone returns a Location that always uses the given zone name and offset (seconds east of UTC).
func LoadLocationFromTZData ¶
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).
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 Time ¶
type Time struct {
// contains filtered or unexported fields
}
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.
func Parse ¶
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.
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.
func Unix ¶ added in v0.9.1
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 UnixMicro ¶ added in v0.9.1
UnixMicro returns the local Time corresponding to the given Unix time, usec microseconds since January 1, 1970 UTC.
func UnixMilli ¶ added in v0.9.1
UnixMilli returns the local Time corresponding to the given Unix time, msec milliseconds since January 1, 1970 UTC.
func (Time) AppendFormat ¶
AppendFormat is like Format but appends the textual representation to b and returns the extended buffer.
func (Time) Compare ¶
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) 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 == with Time values; most code should use Equal instead.
func (Time) Format ¶
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.
func (Time) GoString ¶
GoString implements fmt.GoStringer and formats t to be printed in Go source code.
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) 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) 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 string includes a final field "m=±<value>", where value is the monotonic clock reading formatted as a decimal number of seconds.
The returned string is meant for debugging; for a stable serialized representation, use t.MarshalText, t.MarshalBinary, or t.Format with an explicit format string.
func (Time) Sub ¶ added in v0.9.1
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).
type Timer ¶ added in v0.9.1
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 ¶ added in v0.9.1
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 ¶ added in v0.9.1
NewTimer creates a new Timer that will send the current time on its channel after at least duration d.
func (*Timer) Reset ¶ added in v0.9.1
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 (*Timer) Stop ¶ added in v0.9.1
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.