Functions
Abs
method
#
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.
func (d Duration) Abs() Duration
Add
method
#
Add returns the time t+d.
func (t Time) Add(d Duration) Time
AddDate
method
#
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.
Note that dates are fundamentally coupled to timezones, and calendrical
periods like days don't have fixed durations. AddDate uses the Location of
the Time value to determine these durations. That means that the same
AddDate arguments can produce a different shift in absolute time depending on
the base Time value and its Location. For example, AddDate(0, 0, 1) applied
to 12:00 on March 27 always returns 12:00 on March 28. At some locations and
in some years this is a 24 hour shift. In others it's a 23 hour shift due to
daylight savings time transitions.
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 (t Time) AddDate(years int, months int, days int) Time
After
method
#
After reports whether the time instant t is after u.
func (t Time) After(u Time) bool
After
function
#
After waits for the duration to elapse and then sends the current time
on the returned channel.
It is equivalent to [NewTimer](d).C.
Before Go 1.23, this documentation warned that the underlying
[Timer] would not be recovered by the garbage collector until the
timer fired, and that if efficiency was a concern, code should use
NewTimer instead and call [Timer.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.
func After(d Duration) (<-chan Time)
AfterFunc
function
#
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.
The returned Timer's C field is not used and will be nil.
func AfterFunc(d Duration, f func()) *Timer
AppendBinary
method
#
AppendBinary implements the [encoding.BinaryAppender] interface.
func (t Time) AppendBinary(b []byte) ([]byte, error)
AppendFormat
method
#
AppendFormat is like [Time.Format] but appends the textual
representation to b and returns the extended buffer.
func (t Time) AppendFormat(b []byte, layout string) []byte
AppendText
method
#
AppendText implements the [encoding.TextAppender] interface.
The time is formatted in RFC 3339 format with sub-second precision.
If the timestamp cannot be represented as valid RFC 3339
(e.g., the year is out of range), then an error is returned.
func (t Time) AppendText(b []byte) ([]byte, error)
Before
method
#
Before reports whether the time instant t is before u.
func (t Time) Before(u Time) bool
Clock
method
#
Clock returns the hour, minute, and second within the day specified by t.
func (t Time) Clock() (hour int, min int, sec int)
Compare
method
#
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 (t Time) Compare(u Time) int
Date
method
#
Date returns the year, month, and day in which t occurs.
func (t Time) Date() (year int, month Month, day int)
Date
function
#
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 Date(year int, month Month, day int, hour int, min int, sec int, nsec int, loc *Location) Time
Day
method
#
Day returns the day of the month specified by t.
func (t Time) Day() int
Equal
method
#
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 (t Time) Equal(u Time) bool
Error
method
#
func (f fileSizeError) Error() string
Error
method
#
Error returns the string representation of a ParseError.
func (e *ParseError) Error() string
FixedZone
function
#
FixedZone returns a [Location] that always uses
the given zone name and offset (seconds east of UTC).
func FixedZone(name string, offset int) *Location
Format
method
#
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 (t Time) Format(layout string) string
GoString
method
#
GoString implements [fmt.GoStringer] and formats t to be printed in Go source
code.
func (t Time) GoString() string
GobDecode
method
#
GobDecode implements the gob.GobDecoder interface.
func (t *Time) GobDecode(data []byte) error
GobEncode
method
#
GobEncode implements the gob.GobEncoder interface.
func (t Time) GobEncode() ([]byte, error)
Hour
method
#
Hour returns the hour within the day specified by t, in the range [0, 23].
func (t Time) Hour() int
Hours
method
#
Hours returns the duration as a floating point number of hours.
func (d Duration) Hours() float64
ISOWeek
method
#
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 (t Time) ISOWeek() (year int, week int)
In
method
#
In returns a copy of t representing the same time instant, but
with the copy's location information set to loc for display
purposes.
In panics if loc is nil.
func (t Time) In(loc *Location) Time
IsDST
method
#
IsDST reports whether the time in the configured location is in Daylight Savings Time.
func (t Time) IsDST() bool
IsZero
method
#
IsZero reports whether t represents the zero time instant,
January 1, year 1, 00:00:00 UTC.
func (t Time) IsZero() bool
LoadLocation
function
#
LoadLocation returns the Location with the given name.
If the name is "" or "UTC", LoadLocation returns UTC.
If the name is "Local", LoadLocation returns Local.
Otherwise, the name is taken to be a location name corresponding to a file
in the IANA Time Zone database, such as "America/New_York".
LoadLocation looks for the IANA Time Zone database in the following
locations in order:
- the directory or uncompressed zip file named by the ZONEINFO environment variable
- on a Unix system, the system standard installation location
- $GOROOT/lib/time/zoneinfo.zip
- the time/tzdata package, if it was imported
func LoadLocation(name string) (*Location, error)
LoadLocationFromTZData
function
#
LoadLocationFromTZData returns a Location with the given name
initialized from the IANA Time Zone database-formatted data.
The data should be in the format of a standard IANA time zone file
(for example, the content of /etc/localtime on Unix systems).
func LoadLocationFromTZData(name string, data []byte) (*Location, error)
Local
method
#
Local returns t with the location set to local time.
func (t Time) Local() Time
Location
method
#
Location returns the time zone information associated with t.
func (t Time) Location() *Location
MarshalBinary
method
#
MarshalBinary implements the [encoding.BinaryMarshaler] interface.
func (t Time) MarshalBinary() ([]byte, error)
MarshalJSON
method
#
MarshalJSON implements the [encoding/json.Marshaler] interface.
The time is a quoted string in the RFC 3339 format with sub-second precision.
If the timestamp cannot be represented as valid RFC 3339
(e.g., the year is out of range), then an error is reported.
func (t Time) MarshalJSON() ([]byte, error)
MarshalText
method
#
MarshalText implements the [encoding.TextMarshaler] interface. The output
matches that of calling the [Time.AppendText] method.
See [Time.AppendText] for more information.
func (t Time) MarshalText() ([]byte, error)
Microseconds
method
#
Microseconds returns the duration as an integer microsecond count.
func (d Duration) Microseconds() int64
Milliseconds
method
#
Milliseconds returns the duration as an integer millisecond count.
func (d Duration) Milliseconds() int64
Minute
method
#
Minute returns the minute offset within the hour specified by t, in the range [0, 59].
func (t Time) Minute() int
Minutes
method
#
Minutes returns the duration as a floating point number of minutes.
func (d Duration) Minutes() float64
Month
method
#
Month returns the month of the year specified by t.
func (t Time) Month() Month
Nanosecond
method
#
Nanosecond returns the nanosecond offset within the second specified by t,
in the range [0, 999999999].
func (t Time) Nanosecond() int
Nanoseconds
method
#
Nanoseconds returns the duration as an integer nanosecond count.
func (d Duration) Nanoseconds() int64
NewTicker
function
#
NewTicker returns a new [Ticker] containing a channel that will send
the current time on the channel after each tick. The period of the
ticks is specified by the duration argument. The ticker will adjust
the time interval or drop ticks to make up for slow receivers.
The duration d must be greater than zero; if not, NewTicker will
panic.
Before Go 1.23, the garbage collector did not recover
tickers that had not yet expired or been stopped, so code often
immediately deferred t.Stop after calling NewTicker, to make
the ticker recoverable when it was no longer needed.
As of Go 1.23, the garbage collector can recover unreferenced
tickers, 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.)
func NewTicker(d Duration) *Ticker
NewTimer
function
#
NewTimer creates a new Timer that will send
the current time on its channel after at least duration d.
Before Go 1.23, the garbage collector did not recover
timers that had not yet expired or been stopped, so code often
immediately deferred t.Stop after calling NewTimer, to make
the timer recoverable when it was no longer needed.
As of Go 1.23, the garbage collector can recover unreferenced
timers, 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 was
asynchronous (buffered, capacity 1), which meant that
stale time values could be received even after [Timer.Stop]
or [Timer.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.23
behaviors: when set, unexpired timers won't be garbage collected, and
channels will have buffered capacity. This setting may be removed
in Go 1.27 or later.
func NewTimer(d Duration) *Timer
Now
function
#
Now returns the current local time.
func Now() Time
Parse
function
#
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 Parse(layout string, value string) (Time, error)
ParseDuration
function
#
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 ParseDuration(s string) (Duration, error)
ParseInLocation
function
#
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 ParseInLocation(layout string, value string, loc *Location) (Time, error)
Reset
method
#
Reset stops a ticker and resets its period to the specified duration.
The next tick will arrive after the new period elapses. The duration d
must be greater than zero; if not, Reset will panic.
func (t *Ticker) Reset(d Duration)
Reset
method
#
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 func-based 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.
For a chan-based timer created with NewTimer, as of Go 1.23,
any receive from t.C after Reset has returned is guaranteed not
to receive a time value corresponding to the previous timer settings;
if the program has not received from t.C already and the timer is
running, Reset is guaranteed to return true.
Before Go 1.23, the only safe way to use Reset was to call [Timer.Stop]
and explicitly drain the timer first.
See the [NewTimer] documentation for more details.
func (t *Timer) Reset(d Duration) bool
Round
method
#
Round returns the result of rounding t to the nearest multiple of d (since the zero time).
The rounding behavior for halfway values is to round up.
If d <= 0, Round returns t stripped of any monotonic clock reading but otherwise unchanged.
Round operates on the time as an absolute duration since the
zero time; it does not operate on the presentation form of the
time. Thus, Round(Hour) may return a time with a non-zero
minute, depending on the time's Location.
func (t Time) Round(d Duration) Time
Round
method
#
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 (d Duration) Round(m Duration) Duration
Second
method
#
Second returns the second offset within the minute specified by t, in the range [0, 59].
func (t Time) Second() int
Seconds
method
#
Seconds returns the duration as a floating point number of seconds.
func (d Duration) Seconds() float64
Since
function
#
Since returns the time elapsed since t.
It is shorthand for time.Now().Sub(t).
func Since(t Time) Duration
Sleep
function
#
Sleep pauses the current goroutine for at least the duration d.
A negative or zero duration causes Sleep to return immediately.
func Sleep(d Duration)
Stop
method
#
Stop turns off a ticker. After Stop, no more ticks will be sent.
Stop does not close the channel, to prevent a concurrent goroutine
reading from the channel from seeing an erroneous "tick".
func (t *Ticker) Stop()
Stop
method
#
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.
For a func-based 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.
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 block
rather than receive a stale time value from before the Stop;
if the program has not received from t.C already and the timer is
running, 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 the [NewTimer] documentation for more details.
func (t *Timer) Stop() bool
String
method
#
String returns the English name of the day ("Sunday", "Monday", ...).
func (d Weekday) String() string
String
method
#
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.
func (d Duration) String() string
String
method
#
String returns the English name of the month ("January", "February", ...).
func (m Month) String() string
String
method
#
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=±", 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 (t Time) String() string
String
method
#
String returns a descriptive name for the time zone information,
corresponding to the name argument to [LoadLocation] or [FixedZone].
func (l *Location) String() string
Sub
method
#
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 (t Time) Sub(u Time) Duration
Tick
function
#
Tick is a convenience wrapper for [NewTicker] providing access to the ticking
channel only. Unlike NewTicker, Tick will return nil if d <= 0.
Before Go 1.23, this documentation warned that the underlying
[Ticker] would never be recovered by the garbage collector, and that
if efficiency was a concern, code should use NewTicker instead and
call [Ticker.Stop] when the ticker is no longer needed.
As of Go 1.23, the garbage collector can recover unreferenced
tickers, 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.
func Tick(d Duration) (<-chan Time)
Truncate
method
#
Truncate returns the result of rounding t down to a multiple of d (since the zero time).
If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged.
Truncate operates on the time as an absolute duration since the
zero time; it does not operate on the presentation form of the
time. Thus, Truncate(Hour) may return a time with a non-zero
minute, depending on the time's Location.
func (t Time) Truncate(d Duration) Time
Truncate
method
#
Truncate returns the result of rounding d toward zero to a multiple of m.
If m <= 0, Truncate returns d unchanged.
func (d Duration) Truncate(m Duration) Duration
UTC
method
#
UTC returns t with the location set to UTC.
func (t Time) UTC() Time
Unix
method
#
Unix returns t as a Unix time, the number of seconds elapsed
since January 1, 1970 UTC. The result does not depend on the
location associated with t.
Unix-like operating systems often record time as a 32-bit
count of seconds, but since the method here returns a 64-bit
value it is valid for billions of years into the past or future.
func (t Time) Unix() int64
Unix
function
#
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 Unix(sec int64, nsec int64) Time
UnixMicro
method
#
UnixMicro returns t as a Unix time, the number of microseconds elapsed since
January 1, 1970 UTC. The result is undefined if the Unix time in
microseconds cannot be represented by an int64 (a date before year -290307 or
after year 294246). The result does not depend on the location associated
with t.
func (t Time) UnixMicro() int64
UnixMicro
function
#
UnixMicro returns the local Time corresponding to the given Unix time,
usec microseconds since January 1, 1970 UTC.
func UnixMicro(usec int64) Time
UnixMilli
method
#
UnixMilli returns t as a Unix time, the number of milliseconds elapsed since
January 1, 1970 UTC. The result is undefined if the Unix time in
milliseconds cannot be represented by an int64 (a date more than 292 million
years before or after 1970). The result does not depend on the
location associated with t.
func (t Time) UnixMilli() int64
UnixMilli
function
#
UnixMilli returns the local Time corresponding to the given Unix time,
msec milliseconds since January 1, 1970 UTC.
func UnixMilli(msec int64) Time
UnixNano
method
#
UnixNano returns t as a Unix time, the number of nanoseconds elapsed
since January 1, 1970 UTC. The result is undefined if the Unix time
in nanoseconds cannot be represented by an int64 (a date before the year
1678 or after 2262). Note that this means the result of calling UnixNano
on the zero Time is undefined. The result does not depend on the
location associated with t.
func (t Time) UnixNano() int64
UnmarshalBinary
method
#
UnmarshalBinary implements the [encoding.BinaryUnmarshaler] interface.
func (t *Time) UnmarshalBinary(data []byte) error
UnmarshalJSON
method
#
UnmarshalJSON implements the [encoding/json.Unmarshaler] interface.
The time must be a quoted string in the RFC 3339 format.
func (t *Time) UnmarshalJSON(data []byte) error
UnmarshalText
method
#
UnmarshalText implements the [encoding.TextUnmarshaler] interface.
The time must be in the RFC 3339 format.
func (t *Time) UnmarshalText(data []byte) error
Until
function
#
Until returns the duration until t.
It is shorthand for t.Sub(time.Now()).
func Until(t Time) Duration
Weekday
method
#
Weekday returns the day of the week specified by t.
func (t Time) Weekday() Weekday
Year
method
#
Year returns the year in which t occurs.
func (t Time) Year() int
YearDay
method
#
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 (t Time) YearDay() int
Zone
method
#
Zone computes the time zone in effect at time t, returning the abbreviated
name of the zone (such as "CET") and its offset in seconds east of UTC.
func (t Time) Zone() (name string, offset int)
ZoneBounds
method
#
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.
func (t Time) ZoneBounds() (start Time, end Time)
abbrev
function
#
abbrev returns the abbreviations to use for the given zone z.
func abbrev(z *syscall.Timezoneinformation) (std string, dst string)
absSec
method
#
absSec returns the time t as an absolute seconds, adjusted by the zone offset.
It is called when computing a presentation property like Month or Hour.
We'd rather call it abs, but there are linknames to abs that make that problematic.
See timeAbs below.
func (t Time) absSec() absSeconds
addSec
method
#
addSec adds d seconds to the time.
func (t *Time) addSec(d int64)
androidLoadTzinfoFromTzdata
function
#
func androidLoadTzinfoFromTzdata(file string, name string) ([]byte, error)
appendFormat
method
#
func (t Time) appendFormat(b []byte, layout string) []byte
appendFormatRFC3339
method
#
func (t Time) appendFormatRFC3339(b []byte, nanos bool) []byte
appendInt
function
#
appendInt appends the decimal form of x to b and returns the result.
If the decimal form (excluding sign) is shorter than width, the result is padded with leading 0's.
Duplicates functionality in strconv, but avoids dependency.
func appendInt(b []byte, x int, width int) []byte
appendNano
function
#
appendNano appends a fractional second, as nanoseconds, to b
and returns the result. The nanosec must be within [0, 999999999].
func appendNano(b []byte, nanosec int, std int) []byte
appendStrictRFC3339
method
#
func (t Time) appendStrictRFC3339(b []byte) ([]byte, error)
appendTo
method
#
func (t Time) appendTo(b []byte, errPrefix string) ([]byte, error)
atoi
function
#
Duplicates functionality in strconv, but avoids dependency.
func atoi(s bytes) (x int, err error)
big4
method
#
func (d *dataIO) big4() (n uint32, ok bool)
big8
method
#
func (d *dataIO) big8() (n uint64, ok bool)
byte
method
#
func (d *dataIO) byte() (n byte, ok bool)
byteString
function
#
Make a string by stopping at the first NUL
func byteString(p []byte) string
clock
method
#
clock returns the hour, minute, and second within the day specified by abs.
func (abs absSeconds) clock() (hour int, min int, sec int)
closefd
function
#
func closefd(fd uintptr)
closefd
function
#
func closefd(fd uintptr)
closefd
function
#
func closefd(fd uintptr)
commaOrPeriod
function
#
func commaOrPeriod(b byte) bool
containsDotDot
function
#
containsDotDot reports whether s contains "..".
func containsDotDot(s string) bool
cutspace
function
#
func cutspace(s string) string
date
method
#
date converts days into standard year, month, day.
func (days absDays) date() (year int, month Month, day int)
dateToAbsDays
function
#
dateToAbsDays takes a standard year/month/day and returns the
number of days from the absolute epoch to that day.
The days argument can be out of range and in particular can be negative.
func dateToAbsDays(year int64, month Month, day int) absDays
days
method
#
days converts absolute seconds to absolute days.
func (abs absSeconds) days() absDays
daysBefore
function
#
daysBefore returns the number of days in a non-leap year before month m.
daysBefore(December+1) returns 365.
func daysBefore(m Month) int
daysIn
function
#
func daysIn(m Month, year int) int
digitsLen
function
#
func digitsLen(std int) int
div
function
#
div divides t by d and returns the quotient parity and remainder.
We don't use the quotient parity anymore (round half up instead of round to even)
but it's still here in case we change our minds.
func div(t Time, d Duration) (qmod2 int, r Duration)
fields
function
#
Copied from strings to avoid a dependency.
func fields(s string) []string
findZone
function
#
func findZone(zones []zone, name string, offset int, isDST bool) int
firstZoneUsed
method
#
firstZoneUsed reports whether the first zone is used by some
transition.
func (l *Location) firstZoneUsed() bool
fixedZone
function
#
func fixedZone(name string, offset int) *Location
fmtFrac
function
#
fmtFrac formats the fraction of v/10**prec (e.g., ".12345") into the
tail of buf, omitting trailing zeros. It omits the decimal
point too when the fraction is 0. It returns the index where the
output bytes begin and the value v/10**prec.
func fmtFrac(buf []byte, v uint64, prec int) (nw int, nv uint64)
fmtInt
function
#
fmtInt formats v into the tail of buf.
It returns the index where the output begins.
func fmtInt(buf []byte, v uint64) int
format
method
#
format formats the representation of d into the end of buf and
returns the offset of the first character.
func (d Duration) format(buf *[32]byte) int
get
method
#
func (l *Location) get() *Location
get2
function
#
get2 returns the little-endian 16-bit value in b.
func get2(b []byte) int
get4
function
#
get4 returns the little-endian 32-bit value in b.
func get4(b []byte) int
getnum
function
#
getnum parses s[0:1] or s[0:2] (fixed forces s[0:2])
as a decimal integer and returns the integer and the
remainder of the string.
func getnum(s string, fixed bool) (int, string, error)
getnum3
function
#
getnum3 parses s[0:1], s[0:2], or s[0:3] (fixed forces s[0:3])
as a decimal integer and returns the integer and the remainder
of the string.
func getnum3(s string, fixed bool) (int, string, error)
goFunc
function
#
func goFunc(arg any, seq uintptr, delta int64)
gorootZoneSource
function
#
func gorootZoneSource(goroot string) (string, bool)
gorootZoneSource
function
#
func gorootZoneSource(goroot string) (string, bool)
gorootZoneSource
function
#
func gorootZoneSource(goroot string) (string, bool)
init
function
#
func init()
initLocal
function
#
func initLocal()
initLocal
function
#
func initLocal()
initLocal
function
#
func initLocal()
initLocal
function
#
func initLocal()
initLocal
function
#
func initLocal()
initLocal
function
#
func initLocal()
initLocal
function
#
func initLocal()
initLocalFromTZI
function
#
func initLocalFromTZI(i *syscall.Timezoneinformation)
interrupt
function
#
for testing: whatever interrupts a sleep
func interrupt()
interrupt
function
#
for testing: whatever interrupts a sleep
func interrupt()
interrupt
function
#
for testing: whatever interrupts a sleep
func interrupt()
isDigit
function
#
isDigit reports whether s[i] is in range and is a decimal digit.
func isDigit(s bytes, i int) bool
isLeap
function
#
func isLeap(year int) bool
isSpace
function
#
func isSpace(r rune) bool
janFeb
method
#
janFeb returns 1 if the March 1-based ayday is in January or February, 0 otherwise.
func (ayday absYday) janFeb() absJanFeb
leadingFraction
function
#
leadingFraction consumes the leading [0-9]* from s.
It is used only for fractions, so does not return an error on overflow,
it just stops accumulating precision.
func leadingFraction(s string) (x uint64, scale float64, rem string)
leadingInt
function
#
leadingInt consumes the leading [0-9]* from s.
func leadingInt(s bytes) (x uint64, rem bytes, err error)
leap
method
#
leap returns 1 if (century, cyear) is a leap year, 0 otherwise.
func (century absCentury) leap(cyear absCyear) absLeap
legacyAbsClock
function
#
go:linkname legacyAbsClock time.absClock
func legacyAbsClock(abs uint64) (hour int, min int, sec int)
legacyAbsDate
function
#
go:linkname legacyAbsDate time.absDate
func legacyAbsDate(abs uint64, full bool) (year int, month Month, day int, yday int)
legacyTimeTimeAbs
function
#
go:linkname legacyTimeTimeAbs time.Time.abs
func legacyTimeTimeAbs(t Time) uint64
lessThanHalf
function
#
lessThanHalf reports whether x+x < y but avoids overflow,
assuming x and y are both positive (Duration is signed).
func lessThanHalf(x Duration, y Duration) bool
loadLocation
function
#
loadLocation returns the Location with the given name from one of
the specified sources. See loadTzinfo for a list of supported sources.
The first timezone data matching the given name that is successfully loaded
and parsed is returned as a Location.
func loadLocation(name string, sources []string) (z *Location, firstErr error)
loadTzinfo
function
#
loadTzinfo returns the time zone information of the time zone
with the given name, from a given source. A source may be a
timezone database directory, tzdata database file or an uncompressed
zip file, containing the contents of such a directory.
func loadTzinfo(name string, source string) ([]byte, error)
loadTzinfoFromDirOrZip
function
#
loadTzinfoFromDirOrZip returns the contents of the file with the given name
in dir. dir can either be an uncompressed zip file, or a directory.
func loadTzinfoFromDirOrZip(dir string, name string) ([]byte, error)
loadTzinfoFromZip
function
#
loadTzinfoFromZip returns the contents of the file with the given name
in the given uncompressed zip file.
func loadTzinfoFromZip(zipfile string, name string) ([]byte, error)
loadZoneDataPlan9
function
#
func loadZoneDataPlan9(s string) (l *Location, err error)
loadZoneFilePlan9
function
#
func loadZoneFilePlan9(name string) (*Location, error)
locabs
method
#
locabs is a combination of the Zone and abs methods,
extracting both return values from a single zone lookup.
func (t Time) locabs() (name string, offset int, abs absSeconds)
lookup
function
#
func lookup(tab []string, val string) (int, string, error)
lookup
method
#
lookup returns information about the time zone in use at an
instant in time expressed as seconds since January 1, 1970 00:00:00 UTC.
The returned information gives the name of the zone (such as "CET"),
the start and end times bracketing sec when that zone is in effect,
the offset in seconds east of UTC (such as -5*60*60), and whether
the daylight savings is being observed at that time.
func (l *Location) lookup(sec int64) (name string, offset int, start int64, end int64, isDST bool)
lookupFirstZone
method
#
lookupFirstZone returns the index of the time zone to use for times
before the first transition time, or when there are no transition
times.
The reference implementation in localtime.c from
https://www.iana.org/time-zones/repository/releases/tzcode2013g.tar.gz
implements the following algorithm for these cases:
1. If the first zone is unused by the transitions, use it.
2. Otherwise, if there are transition times, and the first
transition is to a zone in daylight time, find the first
non-daylight-time zone before and closest to the first transition
zone.
3. Otherwise, use the first zone that is not daylight time, if
there is one.
4. Otherwise, use the first zone.
func (l *Location) lookupFirstZone() int
lookupName
method
#
lookupName returns information about the time zone with
the given name (such as "EST") at the given pseudo-Unix time
(what the given time of day would be in UTC).
func (l *Location) lookupName(name string, unix int64) (offset int, ok bool)
match
function
#
match reports whether s1 and s2 match ignoring case.
It is assumed s1 and s2 are the same length.
func match(s1 string, s2 string) bool
matchZoneKey
function
#
matchZoneKey checks if stdname and dstname match the corresponding key
values "MUI_Std" and "MUI_Dlt" or "Std" and "Dlt" in the kname key stored
under the open registry key zones.
func matchZoneKey(zones registry.Key, kname string, stdname string, dstname string) (matched bool, err2 error)
mono
method
#
mono returns t's monotonic clock reading.
It returns 0 for a missing reading.
This function is used only for testing,
so it's OK that technically 0 is a valid
monotonic clock reading as well.
func (t *Time) mono() int64
month
method
#
month returns the standard Month for (m, janFeb)
func (m absMonth) month(janFeb absJanFeb) Month
newParseError
function
#
newParseError creates a new ParseError.
The provided value and valueElem are cloned to avoid escaping their values.
func newParseError(layout string, value string, layoutElem string, valueElem string, message string) *ParseError
newTimer
function
#
The arg cp is a chan Time, but the declaration in runtime uses a pointer,
so we use a pointer here too. This keeps some tools that aggressively
compare linknamed symbol definitions happier.
go:linkname newTimer
func newTimer(when int64, period int64, f func(any, uintptr, int64), arg any, cp unsafe.Pointer) *Timer
nextStdChunk
function
#
nextStdChunk finds the first occurrence of a std string in
layout and returns the text before, the std string, and the text after.
nextStdChunk should be an internal detail,
but widely used packages access it using linkname.
Notable members of the hall of shame include:
- github.com/searKing/golang/go
Do not remove or change the type signature.
See go.dev/issue/67401.
go:linkname nextStdChunk
func nextStdChunk(layout string) (prefix string, std int, suffix string)
norm
function
#
norm returns nhi, nlo such that
hi * base + lo == nhi * base + nlo
0 <= nlo < base
func norm(hi int, lo int, base int) (nhi int, nlo int)
now
function
#
Provided by package runtime.
now returns the current real time, and is superseded by runtimeNow which returns
the fake synctest clock when appropriate.
now should be an internal detail,
but widely used packages access it using linkname.
Notable members of the hall of shame include:
- gitee.com/quant1x/gox
- github.com/phuslu/log
- github.com/sethvargo/go-limiter
- github.com/ulule/limiter/v3
Do not remove or change the type signature.
See go.dev/issue/67401.
func now() (sec int64, nsec int32, mono int64)
nsec
method
#
nsec returns the time's nanoseconds.
func (t *Time) nsec() int32
open
function
#
func open(name string) (uintptr, error)
open
function
#
func open(name string) (uintptr, error)
open
function
#
func open(name string) (uintptr, error)
parse
function
#
func parse(layout string, value string, defaultLocation *Location, local *Location) (Time, error)
parseGMT
function
#
parseGMT parses a GMT time zone. The input string is known to start "GMT".
The function checks whether that is followed by a sign and a number in the
range -23 through +23 excluding zero.
func parseGMT(value string) int
parseNanoseconds
function
#
func parseNanoseconds(value bytes, nbytes int) (ns int, rangeErrString string, err error)
parseRFC3339
function
#
func parseRFC3339(s bytes, local *Location) (Time, bool)
parseSignedOffset
function
#
parseSignedOffset parses a signed timezone offset (e.g. "+03" or "-04").
The function checks for a signed number in the range -23 through +23 excluding zero.
Returns length of the found offset string or 0 otherwise.
func parseSignedOffset(value string) int
parseStrictRFC3339
function
#
func parseStrictRFC3339(b []byte) (Time, error)
parseTimeZone
function
#
parseTimeZone parses a time zone string and returns its length. Time zones
are human-generated and unpredictable. We can't do precise error checking.
On the other hand, for a correct parse there must be a time zone at the
beginning of the string, so it's almost always true that there's one
there. We look at the beginning of the string for a run of upper-case letters.
If there are more than 5, it's an error.
If there are 4 or 5 and the last is a T, it's a time zone.
If there are 3, it's a time zone.
Otherwise, other than special cases, it's not a time zone.
GMT is special because it can have an hour offset.
func parseTimeZone(value string) (length int, ok bool)
preadn
function
#
func preadn(fd uintptr, buf []byte, off int) error
preadn
function
#
func preadn(fd uintptr, buf []byte, off int) error
preadn
function
#
func preadn(fd uintptr, buf []byte, off int) error
pseudoUnix
function
#
pseudoUnix returns the pseudo-Unix time (seconds since Jan 1 1970 *LOCAL TIME*)
denoted by the system date+time d in the given year.
It is up to the caller to convert this local time into a UTC-based time.
func pseudoUnix(year int, d *syscall.Systemtime) int64
quote
function
#
func quote(s string) string
read
function
#
func read(fd uintptr, buf []byte) (int, error)
read
function
#
func read(fd uintptr, buf []byte) (int, error)
read
function
#
func read(fd uintptr, buf []byte) (int, error)
read
method
#
func (d *dataIO) read(n int) []byte
readFile
function
#
readFile reads and returns the content of the named file.
It is a trivial implementation of os.ReadFile, reimplemented
here to avoid depending on io/ioutil or os.
It returns an error if name exceeds maxFileSize bytes.
func readFile(name string) ([]byte, error)
registerLoadFromEmbeddedTZData
function
#
registerLoadFromEmbeddedTZData is called by the time/tzdata package,
if it is imported.
go:linkname registerLoadFromEmbeddedTZData
func registerLoadFromEmbeddedTZData(f func(string) (string, error))
resetTimer
function
#
go:linkname resetTimer
func resetTimer(t *Timer, when int64, period int64) bool
rest
method
#
rest returns the rest of the data in the buffer.
func (d *dataIO) rest() []byte
runtimeNano
function
#
runtimeNano returns the current value of the runtime clock in nanoseconds.
When called within a synctest.Run bubble, it returns the group's fake clock.
go:linkname runtimeNano
func runtimeNano() int64
runtimeNow
function
#
runtimeNow returns the current time.
When called within a synctest.Run bubble, it returns the group's fake clock.
go:linkname runtimeNow
func runtimeNow() (sec int64, nsec int32, mono int64)
sec
method
#
sec returns the time's seconds since Jan 1 year 1.
func (t *Time) sec() int64
sendTime
function
#
sendTime does a non-blocking send of the current time on c.
func sendTime(c any, seq uintptr, delta int64)
separator
function
#
func separator(std int) byte
setLoc
method
#
setLoc sets the location associated with the time.
func (t *Time) setLoc(loc *Location)
setMono
method
#
setMono sets the monotonic clock reading in t.
If t cannot hold a monotonic clock reading,
because its wall time is too large,
setMono is a no-op.
func (t *Time) setMono(m int64)
skip
function
#
skip removes the given prefix from value,
treating runs of space characters as equivalent.
func skip(value string, prefix string) (string, error)
split
method
#
split splits ayday into absolute month and standard (1-based) day-in-month.
func (ayday absYday) split() (m absMonth, mday int)
split
method
#
split splits days into century, cyear, ayday.
func (days absDays) split() (century absCentury, cyear absCyear, ayday absYday)
startsWithLowerCase
function
#
startsWithLowerCase reports whether the string has a lower-case letter at the beginning.
Its purpose is to prevent matching strings like "Month" when looking for "Mon".
func startsWithLowerCase(str string) bool
stdFracSecond
function
#
The "std" value passed to appendNano contains two packed fields: the number of
digits after the decimal and the separator character (period or comma).
These functions pack and unpack that variable.
func stdFracSecond(code int, n int, c int) int
stopTimer
function
#
go:linkname stopTimer
func stopTimer(*Timer) bool
stripMono
method
#
stripMono strips the monotonic clock reading in t.
func (t *Time) stripMono()
subMono
function
#
func subMono(t int64, u int64) Duration
syncTimer
function
#
syncTimer returns c as an unsafe.Pointer, for passing to newTimer.
If the GODEBUG asynctimerchan has disabled the async timer chan
code, then syncTimer always returns nil, to disable the special
channel code paths in the runtime.
func syncTimer(c chan Time) unsafe.Pointer
toEnglishName
function
#
toEnglishName searches the registry for an English name of a time zone
whose zone names are stdname and dstname and returns the English name.
func toEnglishName(stdname string, dstname string) (string, error)
tzruleTime
function
#
tzruleTime takes a year, a rule, and a timezone offset,
and returns the number of seconds since the start of the year
that the rule takes effect.
func tzruleTime(year int, r rule, off int) int
tzset
function
#
tzset takes a timezone string like the one found in the TZ environment
variable, the time of the last time zone transition expressed as seconds
since January 1, 1970 00:00:00 UTC, and a time expressed the same way.
We call this a tzset string since in C the function tzset reads TZ.
The return values are as for lookup, plus ok which reports whether the
parse succeeded.
func tzset(s string, lastTxSec int64, sec int64) (name string, offset int, start int64, end int64, isDST bool, ok bool)
tzsetName
function
#
tzsetName returns the timezone name at the start of the tzset string s,
and the remainder of s, and reports whether the parsing is OK.
func tzsetName(s string) (string, string, bool)
tzsetNum
function
#
tzsetNum parses a number from a tzset string.
It returns the number, and the remainder of the string, and reports success.
The number must be between min and max.
func tzsetNum(s string, min int, max int) (num int, rest string, ok bool)
tzsetOffset
function
#
tzsetOffset returns the timezone offset at the start of the tzset string s,
and the remainder of s, and reports whether the parsing is OK.
The timezone offset is returned as a number of seconds.
func tzsetOffset(s string) (offset int, rest string, ok bool)
tzsetRule
function
#
tzsetRule parses a rule from a tzset string.
It returns the rule, and the remainder of the string, and reports success.
func tzsetRule(s string) (rule, string, bool)
unixSec
method
#
unixSec returns the time's seconds since Jan 1 1970 (Unix time).
func (t *Time) unixSec() int64
unixTime
function
#
func unixTime(sec int64, nsec int32) Time
weekday
method
#
weekday returns the day of the week specified by days.
func (days absDays) weekday() Weekday
when
function
#
when is a helper function for setting the 'when' field of a runtimeTimer.
It returns what the time will be, in nanoseconds, Duration d in the future.
If d is negative, it is ignored. If the returned value would be less than
zero because of an overflow, MaxInt64 is returned.
func when(d Duration) int64
yday
method
#
yday returns the standard 1-based yday for (ayday, janFeb, leap).
func (ayday absYday) yday(janFeb absJanFeb, leap absLeap) int
year
method
#
year returns the standard year for (century, cyear, janFeb).
func (century absCentury) year(cyear absCyear, janFeb absJanFeb) int
yearYday
method
#
yearYday converts days into the standard year and 1-based yday.
func (days absDays) yearYday() (year int, yday int)