Black Lives Matter. Support the Equal Justice Initiative.

Package time

Overview ▾

Package time provides functionality for measuring and displaying time.

The calendrical calculations always assume a Gregorian calendar, with no leap seconds.

Monotonic Clocks

Operating systems provide both a “wall clock,” which is subject to changes for clock synchronization, and a “monotonic clock,” which is not. The general rule is that the wall clock is for telling time and the monotonic clock is for measuring time. Rather than split the API, in this package the Time returned by time.Now contains both a wall clock reading and a monotonic clock reading; later time-telling operations use the wall clock reading, but later time-measuring operations, specifically comparisons and subtractions, use the monotonic clock reading.

For example, this code always computes a positive elapsed time of approximately 20 milliseconds, even if the wall clock is changed during the operation being timed:

start := time.Now()
... operation that takes 20 milliseconds ...
t := time.Now()
elapsed := t.Sub(start)

Other idioms, such as time.Since(start), time.Until(deadline), and time.Now().Before(deadline), are similarly robust against wall clock resets.

The rest of this section gives the precise details of how operations use monotonic clocks, but understanding those details is not required to use this package.

The Time returned by time.Now contains a monotonic clock reading. If Time t has a monotonic clock reading, t.Add adds the same duration to both the wall clock and monotonic clock readings to compute the result. Because t.AddDate(y, m, d), t.Round(d), and t.Truncate(d) are wall time computations, they always strip any monotonic clock reading from their results. Because t.In, t.Local, and t.UTC are used for their effect on the interpretation of the wall time, they also strip any monotonic clock reading from their results. The canonical way to strip a monotonic clock reading is to use t = t.Round(0).

If Times t and u both contain monotonic clock readings, the operations t.After(u), t.Before(u), t.Equal(u), and t.Sub(u) are carried out using the monotonic clock readings alone, ignoring the wall clock readings. If either t or u contains no monotonic clock reading, these operations fall back to using the wall clock readings.

On some systems the monotonic clock will stop if the computer goes to sleep. On such a system, t.Sub(u) may not accurately reflect the actual time that passed between t and u.

Because the monotonic clock reading has no meaning outside the current process, the serialized forms generated by t.GobEncode, t.MarshalBinary, t.MarshalJSON, and t.MarshalText omit the monotonic clock reading, and t.Format provides no format for it. Similarly, the constructors time.Date, time.Parse, time.ParseInLocation, and time.Unix, as well as the unmarshalers t.GobDecode, t.UnmarshalBinary. t.UnmarshalJSON, and t.UnmarshalText always create times with no monotonic clock reading.

Note that the Go == operator compares not just the time instant but also the Location and the monotonic clock reading. See the documentation for the Time type for a discussion of equality testing for Time values.

For debugging, the result of t.String does include the monotonic clock reading if present. If t != u because of different monotonic clock readings, that difference will be visible when printing t.String() and u.String().

Index ▾

Constants
Variables
func After(d Duration) <-chan Time
func Sleep(d Duration)
func Tick(d Duration) <-chan Time
func absClock(abs uint64) (hour, min, sec int)
func appendInt(b []byte, x int, width int) []byte
func atoi(s string) (x int, err error)
func byteString(p []byte) string
func closefd(fd uintptr)
func containsDotDot(s string) bool
func cutspace(s string) string
func daysIn(m Month, year int) int
func daysSinceEpoch(year int) uint64
func findZone(zones []zone, name string, offset int, isDST bool) int
func fmtFrac(buf []byte, v uint64, prec int) (nw int, nv uint64)
func fmtInt(buf []byte, v uint64) int
func formatNano(b []byte, nanosec uint, n int, trim bool) []byte
func get2(b []byte) int
func get4(b []byte) int
func getnum(s string, fixed bool) (int, string, error)
func getnum3(s string, fixed bool) (int, string, error)
func goFunc(arg interface{}, seq uintptr)
func initLocal()
func interrupt()
func isDigit(s string, i int) bool
func isLeap(year int) bool
func leadingFraction(s string) (x int64, scale float64, rem string)
func leadingInt(s string) (x int64, rem string, err error)
func lessThanHalf(x, y Duration) bool
func loadTzinfo(name string, source string) ([]byte, error)
func loadTzinfoFromDirOrZip(dir, name string) ([]byte, error)
func loadTzinfoFromZip(zipfile, name string) ([]byte, error)
func lookup(tab []string, val string) (int, string, error)
func match(s1, s2 string) bool
func modTimer(t *runtimeTimer, when, period int64, f func(interface{}, uintptr), arg interface{}, seq uintptr)
func nextStdChunk(layout string) (prefix string, std int, suffix string)
func norm(hi, lo, base int) (nhi, nlo int)
func now() (sec int64, nsec int32, mono int64)
func open(name string) (uintptr, error)
func parseGMT(value string) int
func parseNanoseconds(value string, nbytes int) (ns int, rangeErrString string, err error)
func parseSignedOffset(value string) int
func parseTimeZone(value string) (length int, ok bool)
func preadn(fd uintptr, buf []byte, off int) error
func quote(s string) string
func read(fd uintptr, buf []byte) (int, error)
func readFile(name string) ([]byte, error)
func registerLoadFromEmbeddedTZData(f func(string) (string, error))
func resetTimer(*runtimeTimer, int64) bool
func runtimeNano() int64
func sendTime(c interface{}, seq uintptr)
func skip(value, prefix string) (string, error)
func startTimer(*runtimeTimer)
func startsWithLowerCase(str string) bool
func stopTimer(*runtimeTimer) bool
func tzruleTime(year int, r rule, off int) int
func tzset(s string, initEnd, sec int64) (name string, offset int, start, end int64, isDST, ok bool)
func tzsetName(s string) (string, string, bool)
func tzsetNum(s string, min, max int) (num int, rest string, ok bool)
func tzsetOffset(s string) (offset int, rest string, ok bool)
func tzsetRule(s string) (rule, string, bool)
func when(d Duration) int64
type Duration
    func ParseDuration(s string) (Duration, error)
    func Since(t Time) Duration
    func Until(t Time) Duration
    func div(t Time, d Duration) (qmod2 int, r 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
    func FixedZone(name string, offset int) *Location
    func LoadLocation(name string) (*Location, error)
    func LoadLocationFromTZData(name string, data []byte) (*Location, error)
    func loadLocation(name string, sources []string) (z *Location, firstErr error)
    func (l *Location) String() string
    func (l *Location) firstZoneUsed() bool
    func (l *Location) get() *Location
    func (l *Location) lookup(sec int64) (name string, offset int, start, end int64)
    func (l *Location) lookupFirstZone() int
    func (l *Location) lookupName(name string, unix int64) (offset int, ok bool)
type Month
    func absDate(abs uint64, full bool) (year int, month Month, day int, yday int)
    func (m Month) String() string
type ParseError
    func (e *ParseError) Error() string
type Ticker
    func NewTicker(d Duration) *Ticker
    func (t *Ticker) Reset(d Duration)
    func (t *Ticker) Stop()
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 parse(layout, value string, defaultLocation, local *Location) (Time, error)
    func unixTime(sec int64, nsec int32) 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)
    func (t Time) abs() uint64
    func (t *Time) addSec(d int64)
    func (t Time) date(full bool) (year int, month Month, day int, yday int)
    func (t Time) locabs() (name string, offset int, abs uint64)
    func (t *Time) mono() int64
    func (t *Time) nsec() int32
    func (t *Time) sec() int64
    func (t *Time) setLoc(loc *Location)
    func (t *Time) setMono(m int64)
    func (t *Time) stripMono()
    func (t *Time) unixSec() int64
type Timer
    func AfterFunc(d Duration, f func()) *Timer
    func NewTimer(d Duration) *Timer
    func (t *Timer) Reset(d Duration) bool
    func (t *Timer) Stop() bool
type Weekday
    func absWeekday(abs uint64) Weekday
    func (d Weekday) String() string
type dataIO
    func (d *dataIO) big4() (n uint32, ok bool)
    func (d *dataIO) big8() (n uint64, ok bool)
    func (d *dataIO) byte() (n byte, ok bool)
    func (d *dataIO) read(n int) []byte
    func (d *dataIO) rest() []byte
type fileSizeError
    func (f fileSizeError) Error() string
type rule
type ruleKind
type runtimeTimer
type zone
type zoneTrans

Package files

format.go sleep.go sys_unix.go tick.go time.go zoneinfo.go zoneinfo_read.go zoneinfo_unix.go

Constants

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.

Some valid layouts are invalid time values for time.Parse, due to formats such as _ for space padding and Z for zone information.

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 recognized day of week formats are "Mon" and "Monday". The recognized month formats are "Jan" and "January".

The formats 2, _2, and 02 are unpadded, space-padded, and zero-padded day of month. The formats __2 and 002 are space-padded and zero-padded three-character day of year; there is no unpadded day of year format.

Text in the format 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.

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. 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.

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"
)
const (
    _                        = iota
    stdLongMonth             = iota + stdNeedDate  // "January"
    stdMonth                                       // "Jan"
    stdNumMonth                                    // "1"
    stdZeroMonth                                   // "01"
    stdLongWeekDay                                 // "Monday"
    stdWeekDay                                     // "Mon"
    stdDay                                         // "2"
    stdUnderDay                                    // "_2"
    stdZeroDay                                     // "02"
    stdUnderYearDay                                // "__2"
    stdZeroYearDay                                 // "002"
    stdHour                  = iota + stdNeedClock // "15"
    stdHour12                                      // "3"
    stdZeroHour12                                  // "03"
    stdMinute                                      // "4"
    stdZeroMinute                                  // "04"
    stdSecond                                      // "5"
    stdZeroSecond                                  // "05"
    stdLongYear              = iota + stdNeedDate  // "2006"
    stdYear                                        // "06"
    stdPM                    = iota + stdNeedClock // "PM"
    stdpm                                          // "pm"
    stdTZ                    = iota                // "MST"
    stdISO8601TZ                                   // "Z0700"  // prints Z for UTC
    stdISO8601SecondsTZ                            // "Z070000"
    stdISO8601ShortTZ                              // "Z07"
    stdISO8601ColonTZ                              // "Z07:00" // prints Z for UTC
    stdISO8601ColonSecondsTZ                       // "Z07:00:00"
    stdNumTZ                                       // "-0700"  // always numeric
    stdNumSecondsTz                                // "-070000"
    stdNumShortTZ                                  // "-07"    // always numeric
    stdNumColonTZ                                  // "-07:00" // always numeric
    stdNumColonSecondsTZ                           // "-07:00:00"
    stdFracSecond0                                 // ".0", ".00", ... , trailing zeros included
    stdFracSecond9                                 // ".9", ".99", ..., trailing zeros omitted

    stdNeedDate  = 1 << 8             // need month, day, year
    stdNeedClock = 2 << 8             // need hour, minute, second
    stdArgShift  = 16                 // extra argument in high bits, above low stdArgShift
    stdMask      = 1<<stdArgShift - 1 // mask out argument
)
const (
    hasMonotonic = 1 << 63
    maxWall      = wallToInternal + (1<<33 - 1) // year 2157
    minWall      = wallToInternal               // year 1885
    nsecMask     = 1<<30 - 1
    nsecShift    = 30
)
const (
    // The unsigned zero year for internal calculations.
    // Must be 1 mod 400, and times before it will not compute correctly,
    // but otherwise can be changed at will.
    absoluteZeroYear = -292277022399

    // The year of the zero Time.
    // Assumed by the unixToInternal computation below.
    internalYear = 1

    // Offsets to convert between internal and absolute or Unix times.
    absoluteToInternal int64 = (absoluteZeroYear - internalYear) * 365.2425 * secondsPerDay
    internalToAbsolute       = -absoluteToInternal

    unixToInternal int64 = (1969*365 + 1969/4 - 1969/100 + 1969/400) * secondsPerDay
    internalToUnix int64 = -unixToInternal

    wallToInternal int64 = (1884*365 + 1884/4 - 1884/100 + 1884/400) * secondsPerDay
    internalToWall int64 = -wallToInternal
)

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
const (
    Nanosecond  Duration = 1
    Microsecond          = 1000 * Nanosecond
    Millisecond          = 1000 * Microsecond
    Second               = 1000 * Millisecond
    Minute               = 60 * Second
    Hour                 = 60 * Minute
)
const (
    secondsPerMinute = 60
    secondsPerHour   = 60 * secondsPerMinute
    secondsPerDay    = 24 * secondsPerHour
    secondsPerWeek   = 7 * secondsPerDay
    daysPer400Years  = 365*400 + 97
    daysPer100Years  = 365*100 + 24
    daysPer4Years    = 365*4 + 1
)

alpha and omega are the beginning and end of time for zone transitions.

const (
    alpha = -1 << 63  // math.MinInt64
    omega = 1<<63 - 1 // math.MaxInt64
)

Copies of io.Seek* constants to avoid importing "io":

const (
    seekStart   = 0
    seekCurrent = 1
    seekEnd     = 2
)

maxFileSize is the max permitted size of files read by readFile. As reference, the zoneinfo.zip distributed by Go is ~350 KB, so 10MB is overkill.

const maxFileSize = 10 << 20
const timeBinaryVersion byte = 1

Variables

Never printed, just needs to be non-nil for return by atoi.

var atoiError = errors.New("time: invalid number")
var badData = errors.New("malformed time zone information")

daysBefore[m] counts the number of days in a non-leap year before month m begins. There is an entry for m=12, counting the number of days before January of next year (365).

var daysBefore = [...]int32{
    0,
    31,
    31 + 28,
    31 + 28 + 31,
    31 + 28 + 31 + 30,
    31 + 28 + 31 + 30 + 31,
    31 + 28 + 31 + 30 + 31 + 30,
    31 + 28 + 31 + 30 + 31 + 30 + 31,
    31 + 28 + 31 + 30 + 31 + 30 + 31 + 31,
    31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30,
    31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31,
    31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30,
    31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31,
}
var errBad = errors.New("bad value for field") // placeholder not passed to user
var errLeadingInt = errors.New("time: bad [0-9]*") // never printed
var errLocation = errors.New("time: invalid location name")

loadFromEmbeddedTZData is used to load a specific tzdata file from tzdata information embedded in the binary itself. This is set when the time/tzdata package is imported, via registerLoadFromEmbeddedTzdata.

var loadFromEmbeddedTZData func(zipname string) (string, error)

loadTzinfoFromTzdata returns the time zone information of the time zone with the given name, from a tzdata database file as they are typically found on android.

var loadTzinfoFromTzdata func(file, name string) ([]byte, error)
var localOnce sync.Once
var longDayNames = []string{
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
}
var longMonthNames = []string{
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
}
var shortDayNames = []string{
    "Sun",
    "Mon",
    "Tue",
    "Wed",
    "Thu",
    "Fri",
    "Sat",
}
var shortMonthNames = []string{
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec",
}

Monotonic times are reported as offsets from startNano. We initialize startNano to runtimeNano() - 1 so that on systems where monotonic time resolution is fairly low (e.g. Windows 2008 which appears to have a default resolution of 15ms), we avoid ever reporting a monotonic time of 0. (Callers may want to use 0 as "time not set".)

var startNano int64 = runtimeNano() - 1

std0x records the std values for "01", "02", ..., "06".

var std0x = [...]int{stdZeroMonth, stdZeroDay, stdZeroHour12, stdZeroMinute, stdZeroSecond, stdYear}
var unitMap = map[string]int64{
    "ns": int64(Nanosecond),
    "us": int64(Microsecond),
    "µs": int64(Microsecond),
    "μs": int64(Microsecond),
    "ms": int64(Millisecond),
    "s":  int64(Second),
    "m":  int64(Minute),
    "h":  int64(Hour),
}

utcLoc is separate so that get can refer to &utcLoc and ensure that it never returns a nil *Location, even if a badly behaved client has changed UTC.

var utcLoc = Location{name: "UTC"}

Many systems use /usr/share/zoneinfo, Solaris 2 has /usr/share/lib/zoneinfo, IRIX 6 has /usr/lib/locale/TZ.

var zoneSources = []string{
    "/usr/share/zoneinfo/",
    "/usr/share/lib/zoneinfo/",
    "/usr/lib/locale/TZ/",
    runtime.GOROOT() + "/lib/time/zoneinfo.zip",
}
var zoneinfo *string
var zoneinfoOnce sync.Once

func After

func After(d Duration) <-chan Time

After waits for the duration to elapse and then sends the current time on the returned channel. It is equivalent to NewTimer(d).C. The underlying Timer is not recovered by the garbage collector until the timer fires. If efficiency is a concern, use NewTimer instead and call Timer.Stop if the timer is no longer needed.

Example

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.

Example

func Tick

func Tick(d Duration) <-chan Time

Tick is a convenience wrapper for NewTicker providing access to the ticking channel only. While Tick is useful for clients that have no need to shut down the Ticker, be aware that without a way to shut it down the underlying Ticker cannot be recovered by the garbage collector; it "leaks". Unlike NewTicker, Tick will return nil if d <= 0.

Example

func absClock

func absClock(abs uint64) (hour, min, sec int)

absClock is like clock but operates on an absolute time.

func appendInt

func appendInt(b []byte, x int, width int) []byte

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 atoi

func atoi(s string) (x int, err error)

Duplicates functionality in strconv, but avoids dependency.

func byteString

func byteString(p []byte) string

Make a string by stopping at the first NUL

func closefd

func closefd(fd uintptr)

func containsDotDot

func containsDotDot(s string) bool

containsDotDot reports whether s contains "..".

func cutspace

func cutspace(s string) string

func daysIn

func daysIn(m Month, year int) int

func daysSinceEpoch

func daysSinceEpoch(year int) uint64

daysSinceEpoch takes a year and returns the number of days from the absolute epoch to the start of that year. This is basically (year - zeroYear) * 365, but accounting for leap days.

func findZone

func findZone(zones []zone, name string, offset int, isDST bool) int

func fmtFrac

func fmtFrac(buf []byte, v uint64, prec int) (nw int, nv uint64)

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 fmtInt

func fmtInt(buf []byte, v uint64) int

fmtInt formats v into the tail of buf. It returns the index where the output begins.

func formatNano

func formatNano(b []byte, nanosec uint, n int, trim bool) []byte

formatNano appends a fractional second, as nanoseconds, to b and returns the result.

func get2

func get2(b []byte) int

get2 returns the little-endian 16-bit value in b.

func get4

func get4(b []byte) int

get4 returns the little-endian 32-bit value in b.

func getnum

func getnum(s string, fixed bool) (int, string, error)

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 getnum3

func getnum3(s string, fixed bool) (int, string, error)

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 goFunc

func goFunc(arg interface{}, seq uintptr)

func initLocal

func initLocal()

func interrupt

func interrupt()

for testing: whatever interrupts a sleep

func isDigit

func isDigit(s string, i int) bool

isDigit reports whether s[i] is in range and is a decimal digit.

func isLeap

func isLeap(year int) bool

func leadingFraction

func leadingFraction(s string) (x int64, scale float64, rem string)

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 leadingInt

func leadingInt(s string) (x int64, rem string, err error)

leadingInt consumes the leading [0-9]* from s.

func lessThanHalf

func lessThanHalf(x, y Duration) bool

lessThanHalf reports whether x+x < y but avoids overflow, assuming x and y are both positive (Duration is signed).

func loadTzinfo

func loadTzinfo(name string, source string) ([]byte, error)

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 loadTzinfoFromDirOrZip

func loadTzinfoFromDirOrZip(dir, name string) ([]byte, error)

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 loadTzinfoFromZip

func loadTzinfoFromZip(zipfile, name string) ([]byte, error)

loadTzinfoFromZip returns the contents of the file with the given name in the given uncompressed zip file.

func lookup

func lookup(tab []string, val string) (int, string, error)

func match

func match(s1, s2 string) bool

match reports whether s1 and s2 match ignoring case. It is assumed s1 and s2 are the same length.

func modTimer

func modTimer(t *runtimeTimer, when, period int64, f func(interface{}, uintptr), arg interface{}, seq uintptr)

func nextStdChunk

func nextStdChunk(layout string) (prefix string, std int, suffix string)

nextStdChunk finds the first occurrence of a std string in layout and returns the text before, the std string, and the text after.

func norm

func norm(hi, lo, base int) (nhi, nlo int)

norm returns nhi, nlo such that

hi * base + lo == nhi * base + nlo
0 <= nlo < base

func now

func now() (sec int64, nsec int32, mono int64)

Provided by package runtime.

func open

func open(name string) (uintptr, error)

func parseGMT

func parseGMT(value string) int

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 parseNanoseconds

func parseNanoseconds(value string, nbytes int) (ns int, rangeErrString string, err error)

func parseSignedOffset

func parseSignedOffset(value string) int

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 parseTimeZone

func parseTimeZone(value string) (length int, ok bool)

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 preadn

func preadn(fd uintptr, buf []byte, off int) error

func quote

func quote(s string) string

func read

func read(fd uintptr, buf []byte) (int, error)

func readFile

func readFile(name string) ([]byte, error)

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 registerLoadFromEmbeddedTZData

func registerLoadFromEmbeddedTZData(f func(string) (string, error))

registerLoadFromEmbeddedTZData is called by the time/tzdata package, if it is imported.

func resetTimer

func resetTimer(*runtimeTimer, int64) bool

func runtimeNano

func runtimeNano() int64

runtimeNano returns the current value of the runtime clock in nanoseconds.

func sendTime

func sendTime(c interface{}, seq uintptr)

func skip

func skip(value, prefix string) (string, error)

skip removes the given prefix from value, treating runs of space characters as equivalent.

func startTimer

func startTimer(*runtimeTimer)

func startsWithLowerCase

func startsWithLowerCase(str string) bool

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 stopTimer

func stopTimer(*runtimeTimer) bool

func tzruleTime

func tzruleTime(year int, r rule, off int) int

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 tzset

func tzset(s string, initEnd, sec int64) (name string, offset int, start, end int64, isDST, ok bool)

tzset takes a timezone string like the one found in the TZ environment variable, the end 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 tzsetName

func tzsetName(s string) (string, string, bool)

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 tzsetNum

func tzsetNum(s string, min, max int) (num int, rest string, ok bool)

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 tzsetOffset

func tzsetOffset(s string) (offset int, rest string, ok bool)

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 tzsetRule

func tzsetRule(s string) (rule, string, bool)

tzsetRule parses a rule from a tzset string. It returns the rule, and the remainder of the string, and reports success.

func when

func when(d Duration) int64

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.

type Duration

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.

type Duration int64
const (
    minDuration Duration = -1 << 63
    maxDuration Duration = 1<<63 - 1
)

Example

func ParseDuration

func ParseDuration(s string) (Duration, error)

ParseDuration parses a duration string. A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".

Example

10h0m0s
1h10m10s
There are 4210 seconds in 1h10m10s.
There are 1000 nanoseconds in 1µs.
There are 1.00e-06 seconds in 1µs.

func Since

func Since(t Time) Duration

Since returns the time elapsed since t. It is shorthand for time.Now().Sub(t).

func Until 1.8

func Until(t Time) Duration

Until returns the duration until t. It is shorthand for t.Sub(time.Now()).

func div

func div(t Time, d Duration) (qmod2 int, r Duration)

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 (Duration) Hours

func (d Duration) Hours() float64

Hours returns the duration as a floating point number of hours.

Example

I've got 4.5 hours of work left.

func (Duration) Microseconds 1.13

func (d Duration) Microseconds() int64

Microseconds returns the duration as an integer microsecond count.

Example

One second is 1000000 microseconds.

func (Duration) Milliseconds 1.13

func (d Duration) Milliseconds() int64

Milliseconds returns the duration as an integer millisecond count.

Example

One second is 1000 milliseconds.

func (Duration) Minutes

func (d Duration) Minutes() float64

Minutes returns the duration as a floating point number of minutes.

Example

The movie is 90 minutes long.

func (Duration) Nanoseconds

func (d Duration) Nanoseconds() int64

Nanoseconds returns the duration as an integer nanosecond count.

Example

One microsecond is 1000 nanoseconds.

func (Duration) Round 1.9

func (d Duration) Round(m Duration) Duration

Round returns the result of rounding d to the nearest multiple of m. The rounding behavior for halfway values is to round away from zero. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, Round returns the maximum (or minimum) duration. If m <= 0, Round returns d unchanged.

Example

d.Round(   1ns) = 1h15m30.918273645s
d.Round(   1µs) = 1h15m30.918274s
d.Round(   1ms) = 1h15m30.918s
d.Round(    1s) = 1h15m31s
d.Round(    2s) = 1h15m30s
d.Round(  1m0s) = 1h16m0s
d.Round( 10m0s) = 1h20m0s
d.Round(1h0m0s) = 1h0m0s

func (Duration) Seconds

func (d Duration) Seconds() float64

Seconds returns the duration as a floating point number of seconds.

Example

Take off in t-90 seconds.

func (Duration) String

func (d Duration) String() string

String returns a string representing the duration in the form "72h3m0.5s". Leading zero units are omitted. As a special case, durations less than one second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure that the leading digit is non-zero. The zero duration formats as 0s.

Example

1h2m0.3s
300ms

func (Duration) Truncate 1.9

func (d Duration) Truncate(m Duration) Duration

Truncate returns the result of rounding d toward zero to a multiple of m. If m <= 0, Truncate returns d unchanged.

Example

d.Truncate(   1ns) = 1h15m30.918273645s
d.Truncate(   1µs) = 1h15m30.918273s
d.Truncate(   1ms) = 1h15m30.918s
d.Truncate(    1s) = 1h15m30s
d.Truncate(    2s) = 1h15m30s
d.Truncate(  1m0s) = 1h15m0s
d.Truncate( 10m0s) = 1h10m0s
d.Truncate(1h0m0s) = 1h0m0s

type Location

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.

type Location struct {
    name string
    zone []zone
    tx   []zoneTrans

    // The tzdata information can be followed by a string that describes
    // how to handle DST transitions not recorded in zoneTrans.
    // The format is the TZ environment variable without a colon; see
    // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html.
    // Example string, for America/Los_Angeles: PST8PDT,M3.2.0,M11.1.0
    extend string

    // Most lookups will be for the current time.
    // To avoid the binary search through tx, keep a
    // static one-element cache that gives the correct
    // zone for the time when the Location was created.
    // if cacheStart <= t < cacheEnd,
    // lookup can return cacheZone.
    // The units for cacheStart and cacheEnd are seconds
    // since January 1, 1970 UTC, to match the argument
    // to lookup.
    cacheStart int64
    cacheEnd   int64
    cacheZone  *zone
}

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 Local *Location = &localLoc

UTC represents Universal Coordinated Time (UTC).

var UTC *Location = &utcLoc

localLoc is separate so that initLocal can initialize it even if a client has changed Local.

var localLoc Location

Example

true

func FixedZone

func FixedZone(name string, offset int) *Location

FixedZone returns a Location that always uses the given zone name and offset (seconds east of UTC).

Example

The time is: 10 Nov 09 23:00 UTC-8

func LoadLocation

func LoadLocation(name string) (*Location, error)

LoadLocation returns the Location with the given name.

If the name is "" or "UTC", LoadLocation returns UTC. If the name is "Local", LoadLocation returns Local.

Otherwise, the name is taken to be a location name corresponding to a file in the IANA Time Zone database, such as "America/New_York".

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.

Example

2018-08-30 05:00:00 -0700 PDT

func LoadLocationFromTZData 1.10

func LoadLocationFromTZData(name string, data []byte) (*Location, error)

LoadLocationFromTZData returns a Location with the given name initialized from the IANA Time Zone database-formatted data. The data should be in the format of a standard IANA time zone file (for example, the content of /etc/localtime on Unix systems).

func loadLocation

func loadLocation(name string, sources []string) (z *Location, firstErr error)

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 (*Location) String

func (l *Location) String() string

String returns a descriptive name for the time zone information, corresponding to the name argument to LoadLocation or FixedZone.

func (*Location) firstZoneUsed

func (l *Location) firstZoneUsed() bool

firstZoneUsed reports whether the first zone is used by some transition.

func (*Location) get

func (l *Location) get() *Location

func (*Location) lookup

func (l *Location) lookup(sec int64) (name string, offset int, start, end int64)

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 (*Location) lookupFirstZone

func (l *Location) lookupFirstZone() int

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 (*Location) lookupName

func (l *Location) lookupName(name string, unix int64) (offset int, ok bool)

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).

type Month

A Month specifies a month of the year (January = 1, ...).

type Month int
const (
    January Month = 1 + iota
    February
    March
    April
    May
    June
    July
    August
    September
    October
    November
    December
)

Example

func absDate

func absDate(abs uint64, full bool) (year int, month Month, day int, yday int)

absDate is like date but operates on an absolute time.

func (Month) String

func (m Month) String() string

String returns the English name of the month ("January", "February", ...).

type ParseError

ParseError describes a problem parsing a time string.

type ParseError struct {
    Layout     string
    Value      string
    LayoutElem string
    ValueElem  string
    Message    string
}

func (*ParseError) Error

func (e *ParseError) Error() string

Error returns the string representation of a ParseError.

type Ticker

A Ticker holds a channel that delivers “ticks” of a clock at intervals.

type Ticker struct {
    C <-chan Time // The channel on which the ticks are delivered.
    r runtimeTimer
}

func NewTicker

func NewTicker(d Duration) *Ticker

NewTicker returns a new Ticker containing a channel that will send the time on the channel after each tick. The period of the ticks is specified by the duration argument. The ticker will adjust the time interval or drop ticks to make up for slow receivers. The duration d must be greater than zero; if not, NewTicker will panic. Stop the ticker to release associated resources.

Example

func (*Ticker) Reset 1.15

func (t *Ticker) Reset(d Duration)

Reset stops a ticker and resets its period to the specified duration. The next tick will arrive after the new period elapses.

func (*Ticker) Stop

func (t *Ticker) Stop()

Stop turns off a ticker. After Stop, no more ticks will be sent. Stop does not close the channel, to prevent a concurrent goroutine reading from the channel from seeing an erroneous "tick".

type Time

A Time represents an instant in time with nanosecond precision.

Programs using times should typically store and pass them as values, not pointers. That is, time variables and struct fields should be of type time.Time, not *time.Time.

A Time value can be used by multiple goroutines simultaneously except that the methods GobDecode, UnmarshalBinary, UnmarshalJSON and UnmarshalText are not concurrency-safe.

Time instants can be compared using the Before, After, and Equal methods. The Sub method subtracts two instants, producing a Duration. The Add method adds a Time and a Duration, producing a Time.

The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC. As this time is unlikely to come up in practice, the IsZero method gives a simple way of detecting a time that has not been initialized explicitly.

Each Time has associated with it a Location, consulted when computing the presentation form of the time, such as in the Format, Hour, and Year methods. The methods Local, UTC, and In return a Time with a specific location. Changing the location in this way changes only the presentation; it does not change the instant in time being denoted and therefore does not affect the computations described in earlier paragraphs.

Representations of a Time value saved by the GobEncode, MarshalBinary, MarshalJSON, and MarshalText methods store the Time.Location's offset, but not the location name. They therefore lose information about Daylight Saving Time.

In addition to the required “wall clock” reading, a Time may contain an optional reading of the current process's monotonic clock, to provide additional precision for comparison or subtraction. See the “Monotonic Clocks” section in the package documentation for details.

Note that the Go == operator compares not just the time instant but also the Location and the monotonic clock reading. Therefore, Time values should not be used as map or database keys without first guaranteeing that the identical Location has been set for all values, which can be achieved through use of the UTC or Local method, and that the monotonic clock reading has been stripped by setting t = t.Round(0). In general, prefer t.Equal(u) to t == u, since t.Equal uses the most accurate comparison available and correctly handles the case when only one of its arguments has a monotonic clock reading.

type Time struct {
    // wall and ext encode the wall time seconds, wall time nanoseconds,
    // and optional monotonic clock reading in nanoseconds.
    //
    // From high to low bit position, wall encodes a 1-bit flag (hasMonotonic),
    // a 33-bit seconds field, and a 30-bit wall time nanoseconds field.
    // The nanoseconds field is in the range [0, 999999999].
    // If the hasMonotonic bit is 0, then the 33-bit field must be zero
    // and the full signed 64-bit wall seconds since Jan 1 year 1 is stored in ext.
    // If the hasMonotonic bit is 1, then the 33-bit field holds a 33-bit
    // unsigned wall seconds since Jan 1 year 1885, and ext holds a
    // signed 64-bit monotonic clock reading, nanoseconds since process start.
    wall uint64
    ext  int64

    // loc specifies the Location that should be used to
    // determine the minute, hour, month, day, and year
    // that correspond to this Time.
    // The nil location means UTC.
    // All UTC times are represented with loc==nil, never loc==&utcLoc.
    loc *Location
}

func Date

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time

Date returns the Time corresponding to

yyyy-mm-dd hh:mm:ss + nsec nanoseconds

in the appropriate zone for that time in the given location.

The month, day, hour, min, sec, and nsec values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 1.

A daylight savings time transition skips or repeats times. For example, in the United States, March 13, 2011 2:15am never occurred, while November 6, 2011 1:15am occurred twice. In such cases, the choice of time zone, and therefore the time, is not well-defined. Date returns a time that is correct in one of the two zones involved in the transition, but it does not guarantee which.

Date panics if loc is nil.

Example

Go launched at 2009-11-10 15:00:00 -0800 PST

func Now

func Now() Time

Now returns the current local time.

func Parse

func Parse(layout, value string) (Time, error)

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.

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.

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.

Example

2013-02-03 19:54:00 -0800 PST
2013-02-03 00:00:00 +0000 UTC
2006-01-02 15:04:05 +0000 UTC
2006-01-02 15:04:05 +0700 +0700
error parsing time "2006-01-02T15:04:05Z07:00": extra text: "07:00"

func ParseInLocation 1.1

func ParseInLocation(layout, value string, loc *Location) (Time, error)

ParseInLocation is like Parse but differs in two important ways. First, in the absence of time zone information, Parse interprets a time as UTC; ParseInLocation interprets the time as in the given location. Second, when given a zone offset or abbreviation, Parse tries to match it against the Local location; ParseInLocation uses the given location.

Example

2012-07-09 05:02:00 +0200 CEST
2012-07-09 00:00:00 +0200 CEST

func Unix

func Unix(sec int64, nsec int64) Time

Unix returns the local Time corresponding to the given Unix time, sec seconds and nsec nanoseconds since January 1, 1970 UTC. It is valid to pass nsec outside the range [0, 999999999]. Not all sec values have a corresponding time value. One such value is 1<<63-1 (the largest int64 value).

func parse

func parse(layout, value string, defaultLocation, local *Location) (Time, error)

func unixTime

func unixTime(sec int64, nsec int32) Time

func (Time) Add

func (t Time) Add(d Duration) Time

Add returns the time t+d.

Example

start = 2009-01-01 12:00:00 +0000 UTC
start.Add(time.Second * 10) = 2009-01-01 12:00:10 +0000 UTC
start.Add(time.Minute * 10) = 2009-01-01 12:10:00 +0000 UTC
start.Add(time.Hour * 10) = 2009-01-01 22:00:00 +0000 UTC
start.Add(time.Hour * 24 * 10) = 2009-01-11 12:00:00 +0000 UTC

func (Time) AddDate

func (t Time) AddDate(years int, months int, days int) Time

AddDate returns the time corresponding to adding the given number of years, months, and days to t. For example, AddDate(-1, 2, 3) applied to January 1, 2011 returns March 4, 2010.

AddDate normalizes its result in the same way that Date does, so, for example, adding one month to October 31 yields December 1, the normalized form for November 31.

Example

oneDayLater: start.AddDate(0, 0, 1) = 2009-01-02 00:00:00 +0000 UTC
oneMonthLater: start.AddDate(0, 1, 0) = 2009-02-01 00:00:00 +0000 UTC
oneYearLater: start.AddDate(1, 0, 0) = 2010-01-01 00:00:00 +0000 UTC

func (Time) After

func (t Time) After(u Time) bool

After reports whether the time instant t is after u.

Example

year3000.After(year2000) = true
year2000.After(year3000) = false

func (Time) AppendFormat 1.5

func (t Time) AppendFormat(b []byte, layout string) []byte

AppendFormat is like Format but appends the textual representation to b and returns the extended buffer.

Example

Time: 11:00AM

func (Time) Before

func (t Time) Before(u Time) bool

Before reports whether the time instant t is before u.

Example

year2000.Before(year3000) = true
year3000.Before(year2000) = false

func (Time) Clock

func (t Time) Clock() (hour, min, sec int)

Clock returns the hour, minute, and second within the day specified by t.

func (Time) Date

func (t Time) Date() (year int, month Month, day int)

Date returns the year, month, and day in which t occurs.

Example

year = 2000
month = February
day = 1

func (Time) Day

func (t Time) Day() int

Day returns the day of the month specified by t.

Example

day = 1

func (Time) Equal

func (t Time) Equal(u Time) bool

Equal reports whether t and u represent the same time instant. Two times can be equal even if they are in different locations. For example, 6:00 +0200 and 4:00 UTC are Equal. See the documentation on the Time type for the pitfalls of using == with Time values; most code should use Equal instead.

Example

datesEqualUsingEqualOperator = false
datesEqualUsingFunction = true

func (Time) Format

func (t Time) Format(layout string) string

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

default format: 2015-02-25 11:06:39 -0800 PST
Unix format: Wed Feb 25 11:06:39 PST 2015
Same, in UTC: Wed Feb 25 19:06:39 UTC 2015

Formats:

Basic full date  "Mon Jan 2 15:04:05 MST 2006" gives "Wed Feb 25 11:06:39 PST 2015"
Basic short date "2006/01/02" gives "2015/02/25"
AM/PM            "3PM==3pm==15h" gives "11AM==11am==11h"
No fraction      "Mon Jan _2 15:04:05 MST 2006" gives "Wed Feb 25 11:06:39 PST 2015"
0s for fraction  "15:04:05.00000" gives "11:06:39.12340"
9s for fraction  "15:04:05.99999999" gives "11:06:39.1234"

Example (Pad)

Unix             "Mon Jan _2 15:04:05 MST 2006" gives "Sat Mar  7 11:06:39 PST 2015"
No pad           "<2>" gives "<7>"
Spaces           "<_2>" gives "< 7>"
Zeros            "<02>" gives "<07>"
Suppressed pad   "04:05" gives "06:39"

func (*Time) GobDecode

func (t *Time) GobDecode(data []byte) error

GobDecode implements the gob.GobDecoder interface.

func (Time) GobEncode

func (t Time) GobEncode() ([]byte, error)

GobEncode implements the gob.GobEncoder interface.

func (Time) Hour

func (t Time) Hour() int

Hour returns the hour within the day specified by t, in the range [0, 23].

func (Time) ISOWeek

func (t Time) ISOWeek() (year, week int)

ISOWeek returns the ISO 8601 year and week number in which t occurs. Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 of year n+1.

func (Time) In

func (t Time) In(loc *Location) Time

In returns a copy of t representing the same time instant, but with the copy's location information set to loc for display purposes.

In panics if loc is nil.

func (Time) IsZero

func (t Time) IsZero() bool

IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.

func (Time) Local

func (t Time) Local() Time

Local returns t with the location set to local time.

func (Time) Location

func (t Time) Location() *Location

Location returns the time zone information associated with t.

func (Time) MarshalBinary 1.2

func (t Time) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface.

func (Time) MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)

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 1.2

func (t Time) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface. The time is formatted in RFC 3339 format, with sub-second precision added if present.

func (Time) Minute

func (t Time) Minute() int

Minute returns the minute offset within the hour specified by t, in the range [0, 59].

func (Time) Month

func (t Time) Month() Month

Month returns the month of the year specified by t.

func (Time) Nanosecond

func (t Time) Nanosecond() int

Nanosecond returns the nanosecond offset within the second specified by t, in the range [0, 999999999].

func (Time) Round 1.1

func (t Time) Round(d Duration) Time

Round returns the result of rounding t to the nearest multiple of d (since the zero time). The rounding behavior for halfway values is to round up. If d <= 0, Round returns t stripped of any monotonic clock reading but otherwise unchanged.

Round operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time. Thus, Round(Hour) may return a time with a non-zero minute, depending on the time's Location.

Example

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

func (t Time) Second() int

Second returns the second offset within the minute specified by t, in the range [0, 59].

func (Time) String

func (t Time) String() string

String returns the time formatted using the format string

"2006-01-02 15:04:05.999999999 -0700 MST"

If the time has a monotonic clock reading, the returned string includes a final field "m=±<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.

Example

withNanoseconds = 2000-02-01 12:13:14.000000015 +0000 UTC
withoutNanoseconds = 2000-02-01 12:13:14 +0000 UTC

func (Time) Sub

func (t Time) Sub(u Time) Duration

Sub returns the duration t-u. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, the maximum (or minimum) duration will be returned. To compute t-d for a duration d, use t.Add(-d).

Example

difference = 12h0m0s

func (Time) Truncate 1.1

func (t Time) Truncate(d Duration) Time

Truncate returns the result of rounding t down to a multiple of d (since the zero time). If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged.

Truncate operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time. Thus, Truncate(Hour) may return a time with a non-zero minute, depending on the time's Location.

Example

t.Truncate(  1ns) = 12:15:30.918273645
t.Truncate(  1µs) = 12:15:30.918273
t.Truncate(  1ms) = 12:15:30.918
t.Truncate(   1s) = 12:15:30
t.Truncate(   2s) = 12:15:30
t.Truncate( 1m0s) = 12:15:00
t.Truncate(10m0s) = 12:10:00

func (Time) UTC

func (t Time) UTC() Time

UTC returns t with the location set to UTC.

func (Time) Unix

func (t Time) Unix() int64

Unix returns t as a Unix time, the number of seconds elapsed since January 1, 1970 UTC. The result does not depend on the location associated with t. Unix-like operating systems often record time as a 32-bit count of seconds, but since the method here returns a 64-bit value it is valid for billions of years into the past or future.

Example

2001-09-09 01:46:40 +0000 UTC
2001-09-09 01:46:40 +0000 UTC
2001-09-09 01:46:40 +0000 UTC
1000000000
1000000000000000000

func (Time) UnixNano

func (t Time) UnixNano() int64

UnixNano returns t as a Unix time, the number of nanoseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in nanoseconds cannot be represented by an int64 (a date before the year 1678 or after 2262). Note that this means the result of calling UnixNano on the zero Time is undefined. The result does not depend on the location associated with t.

func (*Time) UnmarshalBinary 1.2

func (t *Time) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface. The time is expected to be a quoted string in RFC 3339 format.

func (*Time) UnmarshalText 1.2

func (t *Time) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. The time is expected to be in RFC 3339 format.

func (Time) Weekday

func (t Time) Weekday() Weekday

Weekday returns the day of the week specified by t.

func (Time) Year

func (t Time) Year() int

Year returns the year in which t occurs.

func (Time) YearDay 1.1

func (t Time) YearDay() int

YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years, and [1,366] in leap years.

func (Time) Zone

func (t Time) Zone() (name string, offset int)

Zone computes the time zone in effect at time t, returning the abbreviated name of the zone (such as "CET") and its offset in seconds east of UTC.

func (Time) abs

func (t Time) abs() uint64

abs returns the time t as an absolute time, adjusted by the zone offset. It is called when computing a presentation property like Month or Hour.

func (*Time) addSec

func (t *Time) addSec(d int64)

addSec adds d seconds to the time.

func (Time) date

func (t Time) date(full bool) (year int, month Month, day int, yday int)

date computes the year, day of year, and when full=true, the month and day in which t occurs.

func (Time) locabs

func (t Time) locabs() (name string, offset int, abs uint64)

locabs is a combination of the Zone and abs methods, extracting both return values from a single zone lookup.

func (*Time) mono

func (t *Time) mono() int64

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 (*Time) nsec

func (t *Time) nsec() int32

nsec returns the time's nanoseconds.

func (*Time) sec

func (t *Time) sec() int64

sec returns the time's seconds since Jan 1 year 1.

func (*Time) setLoc

func (t *Time) setLoc(loc *Location)

setLoc sets the location associated with the time.

func (*Time) setMono

func (t *Time) setMono(m int64)

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 (*Time) stripMono

func (t *Time) stripMono()

stripMono strips the monotonic clock reading in t.

func (*Time) unixSec

func (t *Time) unixSec() int64

unixSec returns the time's seconds since Jan 1 1970 (Unix time).

type Timer

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.

type Timer struct {
    C <-chan Time
    r runtimeTimer
}

func AfterFunc

func AfterFunc(d Duration, f func()) *Timer

AfterFunc waits for the duration to elapse and then calls f in its own goroutine. It returns a Timer that can be used to cancel the call using its Stop method.

func NewTimer

func NewTimer(d Duration) *Timer

NewTimer creates a new Timer that will send the current time on its channel after at least duration d.

func (*Timer) Reset 1.1

func (t *Timer) Reset(d Duration) bool

Reset changes the timer to expire after duration d. It returns true if the timer had been active, false if the timer had expired or been stopped.

For a Timer created with NewTimer, Reset should be invoked only on stopped or expired timers with drained channels.

If a program has already received a value from t.C, the timer is known to have expired and the channel drained, so t.Reset can be used directly. If a program has not yet received a value from t.C, however, the timer must be stopped and—if Stop reports that the timer expired before being stopped—the channel explicitly drained:

if !t.Stop() {
	<-t.C
}
t.Reset(d)

This should not be done concurrent to other receives from the Timer's channel.

Note that it is not possible to use Reset's return value correctly, as there is a race condition between draining the channel and the new timer expiring. Reset should always be invoked on stopped or expired channels, as described above. The return value exists to preserve compatibility with existing programs.

For a Timer created with AfterFunc(d, f), Reset either reschedules when f will run, in which case Reset returns true, or schedules f to run again, in which case it returns false. When Reset returns false, Reset neither waits for the prior f to complete before returning nor does it guarantee that the subsequent goroutine running f does not run concurrently with the prior one. If the caller needs to know whether the prior execution of f is completed, it must coordinate with f explicitly.

func (*Timer) Stop

func (t *Timer) Stop() bool

Stop prevents the Timer from firing. It returns true if the call stops the timer, false if the timer has already expired or been stopped. Stop does not close the channel, to prevent a read from the channel succeeding incorrectly.

To ensure the channel is empty after a call to Stop, check the return value and drain the channel. For example, assuming the program has not received from t.C already:

if !t.Stop() {
	<-t.C
}

This cannot be done concurrent to other receives from the Timer's channel or other calls to the Timer's Stop method.

For a timer created with AfterFunc(d, f), if t.Stop returns false, then the timer has already expired and the function f has been started in its own goroutine; Stop does not wait for f to complete before returning. If the caller needs to know whether f is completed, it must coordinate with f explicitly.

type Weekday

A Weekday specifies a day of the week (Sunday = 0, ...).

type Weekday int
const (
    Sunday Weekday = iota
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday
)

func absWeekday

func absWeekday(abs uint64) Weekday

absWeekday is like Weekday but operates on an absolute time.

func (Weekday) String

func (d Weekday) String() string

String returns the English name of the day ("Sunday", "Monday", ...).

type dataIO

Simple I/O interface to binary blob of data.

type dataIO struct {
    p     []byte
    error bool
}

func (*dataIO) big4

func (d *dataIO) big4() (n uint32, ok bool)

func (*dataIO) big8

func (d *dataIO) big8() (n uint64, ok bool)

func (*dataIO) byte

func (d *dataIO) byte() (n byte, ok bool)

func (*dataIO) read

func (d *dataIO) read(n int) []byte

func (*dataIO) rest

func (d *dataIO) rest() []byte

read returns the read of the data in the buffer.

type fileSizeError

type fileSizeError string

func (fileSizeError) Error

func (f fileSizeError) Error() string

type rule

rule is a rule read from a tzset string.

type rule struct {
    kind ruleKind
    day  int
    week int
    mon  int
    time int // transition time
}

type ruleKind

ruleKind is the kinds of rules that can be seen in a tzset string.

type ruleKind int
const (
    ruleJulian ruleKind = iota
    ruleDOY
    ruleMonthWeekDay
)

type runtimeTimer

Interface to timers implemented in package runtime. Must be in sync with ../runtime/time.go:/^type timer

type runtimeTimer struct {
    pp       uintptr
    when     int64
    period   int64
    f        func(interface{}, uintptr) // NOTE: must not be closure
    arg      interface{}
    seq      uintptr
    nextwhen int64
    status   uint32
}

type zone

A zone represents a single time zone such as CET.

type zone struct {
    name   string // abbreviated name, "CET"
    offset int    // seconds east of UTC
    isDST  bool   // is this zone Daylight Savings Time?
}

type zoneTrans

A zoneTrans represents a single time zone transition.

type zoneTrans struct {
    when         int64 // transition time, in seconds since 1970 GMT
    index        uint8 // the index of the zone that goes into effect at that time
    isstd, isutc bool  // ignored - no idea what these mean
}

Subdirectories

Name Synopsis
..
tzdata Package tzdata provides an embedded copy of the timezone database.