time
52 分钟阅读
Package time provides functionality for measuring and displaying time.
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.
操作系统提供了“挂钟(wall clock)”和“单调钟(monotonic clock)”两种时钟,前者会受到时间同步的影响,后者则不会。一般规则是挂钟用于显示时间,而单调钟用于计时。为了不分割API,在这个包中,time.Now返回的时间包含了挂钟读数和单调钟读数;后续的时间显示操作使用挂钟读数,而后续的时间计算操作,特别是比较和减法操作,使用单调钟读数。
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:
例如,即使在计时操作中挂钟被更改,以下代码始终计算出大约20毫秒的正计时:
| |
Other idioms, such as time.Since(start), time.Until(deadline), and time.Now().Before(deadline), are similarly robust against wall clock resets.
其他的习语,比如time.Since(start),time.Until(deadline),和time.Now().Before(deadline),同样能够很好地应对挂钟重置的情况。
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).
time.Now返回的Time包含一个单调钟读数。如果Time t具有单调钟读数,则t.Add会将相同的持续时间添加到挂钟和单调钟读数中,以计算结果。因为t.AddDate(y, m, d),t.Round(d),和t.Truncate(d)都是针对挂钟时间的计算,它们总是从结果中剥离任何单调钟读数。因为t.In,t.Local,和t.UTC用于影响挂钟时间解释的效果,它们也会从结果中剥离任何单调钟读数。剥离单调钟读数的规范方法是使用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), t.Compare(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.
如果Times t和u都包含单调钟读数,则操作t.After(u),t.Before(u),t.Equal(u),t.Compare(u),和t.Sub(u)仅使用单调钟读数进行计算,忽略挂钟读数。如果t或u中没有单调钟读数,则这些操作将回退到使用挂钟读数。
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.
在某些系统上,如果计算机进入睡眠状态,单调钟会停止。在这种情况下,t.Sub(u)可能无法准确反映t和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.
由于单调钟读数在当前进程之外没有意义,因此t.GobEncode、t.MarshalBinary、t.MarshalJSON和t.MarshalText生成的序列化形式都省略了单调钟读数,而t.Format则不提供任何格式。同样,构造函数time.Date、time.Parse、time.ParseInLocation和time.Unix,以及解码器t.GobDecode、t.UnmarshalBinary、t.UnmarshalJSON和t.UnmarshalText始终创建没有单调钟读数的时间。
The monotonic clock reading exists only in Time values. It is not a part of Duration values or the Unix times returned by t.Unix and friends.
单调钟读数仅存在于Time值中。它不是Duration值或t.Unix和相关函数返回的Unix时间的一部分。
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.
请注意,Go的==运算符不仅比较时间瞬间,还比较Location (时区)和单调钟读数。有关Time值的相等性测试的讨论,请参阅Time类型的文档。
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().
为了调试,如果存在单调钟读数,则t.String的结果会包含该读数。如果t != u,因为具有不同的单调钟读数,那么在打印t.String()和u.String()时将可见这种差异。
计时器的精度 Timer Resolution
Timer resolution varies depending on the Go runtime, the operating system and the underlying hardware. On Unix, the resolution is ~1ms. On Windows version 1803 and newer, the resolution is ~0.5ms. On older Windows versions, the default resolution is ~16ms, but a higher resolution may be requested using golang.org/x/sys/windows.TimeBeginPeriod.
计时器 的精度取决于 Go 运行时、操作系统以及底层硬件。在 Unix 系统中,计时器的精度约为 1 毫秒。在 Windows 1803 及更新版本中,精度约为 0.5 毫秒。在较早的 Windows 版本中,默认精度约为 16 毫秒,但可以通过使用 golang.org/x/sys/windows.TimeBeginPeriod 请求更高的精度。
常量
| |
These are predefined layouts for use in Time.Format and time.Parse. The reference time used in these layouts is the specific time stamp:
这些是用于Time.Format和time.Parse的预定义布局。这些布局中使用的参考时间是特定的时间戳:
01/02 03:04:05PM '06 -0700
(January 2, 15:04:05, 2006, in time zone seven hours west of GMT). That value is recorded as the constant named Layout, listed below. As a Unix time, this is 1136239445. Since MST is GMT-0700, the reference would be printed by the Unix date command as:
(2006年1月2日,15:04:05,位于GMT西七小时的时区)。该值被记录为名为Layout的常量,如下所示。作为Unix时间,这是1136239445。由于MST是GMT-0700,Unix date命令将打印出该参考值:
Mon Jan 2 15:04:05 MST 2006
It is a regrettable historic error that the date uses the American convention of putting the numerical month before the day.
令人遗憾的是,该日期使用将数字月份放在日前的美国惯例。
The example for Time.Format demonstrates the working of the layout string in detail and is a good reference.
Time.Format 的示例详细演示了布局字符串的工作方式,是一个很好的参考。
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.
请注意,RFC822、RFC850 和 RFC1123 格式应仅应用于本地时间。将它们应用于 UTC 时间将使用 “UTC” 作为时区缩写,而严格来说,这些 RFC 要求在这种情况下使用 “GMT”。通常应该使用 RFC1123Z 替代 RFC1123,用于坚持该格式的服务器,并且应该为新协议首选 RFC3339。RFC3339、RFC822、RFC822Z、RFC1123 和 RFC1123Z 适用于格式化;与 time.Parse 一起使用时,它们不接受 RFC 允许的所有时间格式,并且它们接受形式上未定义的时间格式。RFC3339Nano 格式从秒字段中删除尾随的零,因此一旦格式化,可能无法正确排序。
Most programs can use one of the defined constants as the layout passed to Format or Parse. The rest of this comment can be ignored unless you are creating a custom layout string.
大多数程序可以使用定义的常量之一作为传递给 Format 或 Parse 的布局。除非您要创建自定义布局字符串,否则可以忽略此注释的其余部分。
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.
要定义自己的格式,请编写引用时间以您的方式格式化的样子;请参阅 ANSIC、StampMicro 或 Kitchen 等常量的值。模型是演示引用时间的外观,以便 Format 和 Parse 方法可以将相同的转换应用于一般时间值。
Here is a summary of the components of a layout string. Each element shows by example the formatting of an element of the reference time. Only these values are recognized. Text in the layout string that is not recognized as part of the reference time is echoed verbatim during Format and expected to appear verbatim in the input to Parse.
以下是布局字符串的组件摘要。每个元素都以示例形式显示了参考时间的一个元素的格式。仅识别这些值。布局字符串中未被识别为参考时间的文本在 Format 中被回显,并期望在 Parse 的输入中以原样出现。
It is a regrettable historic error that the date uses the American convention of putting the numerical month before the day.
这是一个令人遗憾的历史错误,日期使用了美国的习惯,在日期之前放置数字月份。
The example for Time.Format demonstrates the working of the layout string in detail and is a good reference.
Time.Format的示例详细演示了布局字符串的工作原理,是一个很好的参考。
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.
请注意,RFC822、RFC850和RFC1123格式仅适用于本地时间。将它们应用于UTC时间将使用"UTC"作为时区缩写,严格来说,这些RFC要求在这种情况下使用"GMT"。一般应该使用RFC1123Z而不是RFC1123,以满足一些服务器对该格式的要求,并且对于新协议应该优先选择RFC3339。RFC3339、RFC822、RFC822Z、RFC1123和RFC1123Z适用于格式化;当与time.Parse一起使用时,它们不接受RFC允许的所有时间格式,但可以接受未正式定义的时间格式。RFC3339Nano格式从秒字段中去除尾随的零,因此一旦格式化可能无法正确排序。
Most programs can use one of the defined constants as the layout passed to Format or Parse. The rest of this comment can be ignored unless you are creating a custom layout string.
大多数程序可以使用定义的常量之一作为传递给Format或Parse的布局。除非您正在创建自定义布局字符串,否则可以忽略此注释的其余部分。
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.
为了定义自己的格式,请按照您的方式编写参考时间的格式;参考ANSIC、StampMicro或Kitchen等常量的值以获取示例。该模型旨在演示参考时间的样式,以便Format和Parse方法可以将相同的转换应用于一般时间值。
Here is a summary of the components of a layout string. Each element shows by example the formatting of an element of the reference time. Only these values are recognized. Text in the layout string that is not recognized as part of the reference time is echoed verbatim during Format and expected to appear verbatim in the input to Parse.
以下是布局字符串的组成部分的摘要。每个元素都通过示例显示了参考时间的格式化方式。只有这些值会被识别。布局字符串中未被识别为参考时间部分的文本在Format期间会被原样回显,并且期望在Parse的输入中原样出现。
Year: "2006" "06"
Month: "Jan" "January" "01" "1"
Day of the week: "Mon" "Monday"
Day of the month: "2" "_2" "02"
Day of the year: "__2" "002"
Hour: "15" "3" "03" (PM or AM)
Minute: "4" "04"
Second: "5" "05"
AM/PM mark: "PM"
Numeric time zone offsets format as follows:
数字时区偏移的格式如下:
"-0700" ±hhmm
"-07:00" ±hh:mm
"-07" ±hh
"-070000" ±hhmmss
"-07:00:00" ±hh:mm:ss
Replacing the sign in the format with a Z triggers the ISO 8601 behavior of printing Z instead of an offset for the UTC zone. Thus:
用 Z 替换格式中的符号会触发 ISO 8601 的行为,打印 Z 代替 UTC 时区的偏移。因此:
用Z替换格式中的符号会触发ISO 8601的行为,将Z打印为UTC时区的偏移量。因此:
将格式中的符号替换为 Z 会触发 ISO 8601 行为,即在 UTC 时区打印 Z 而不是时区偏移。因此:
"Z0700" Z or ±hhmm
"Z07:00" Z or ±hh:mm
"Z07" Z or ±hh
"Z070000" Z or ±hhmmss
"Z07:00:00" Z or ±hh:mm:ss
Within the format string, the underscores in “_2” and “__2” represent spaces that may be replaced by digits if the following number has multiple digits, for compatibility with fixed-width Unix time formats. A leading zero represents a zero-padded value.
在格式字符串中,"_2" 和 “__2“中的下划线表示空格,如果后面的数字有多个数字,则可以替换为空格,以与固定宽度的Unix时间格式兼容。前导零表示零填充值。
The formats __2 and 002 are space-padded and zero-padded three-character day of year; there is no unpadded day of year format.
格式 __2 和 002 是以空格填充和以零填充的三位数年份的格式;没有未填充的年份格式。
A comma or decimal point followed by one or more zeros represents a fractional second, printed to the given number of decimal places. A comma or decimal point followed by one or more nines represents a fractional second, printed to the given number of decimal places, with trailing zeros removed. For example “15:04:05,000” or “15:04:05.000” formats or parses with millisecond precision.
逗号或小数点后面跟着一个或多个零表示小数秒,打印到指定的小数位数。逗号或小数点后面跟着一个或多个九表示小数秒,打印到指定的小数位数,并去掉尾随的零。例如,“15:04:05,000” 或"15:04:05.000"格式可以用毫秒精度进行打印或解析。
Some valid layouts are invalid time values for time.Parse, due to formats such as _ for space padding and Z for zone information.
一些有效的布局对于 time.Parse 来说是无效的时间值,原因是格式中使用了 _ 进行空格填充和 Z 进行时区信息的表示。
| |
Common durations. There is no definition for units of Day or larger to avoid confusion across daylight savings time zone transitions.
常见的时间段。为了避免在夏令时区转换中产生混淆,没有对Day (天)或更长时间单位进行定义。
To count the number of units in a Duration, divide:
要计算Duration (持续时间)中的单位数量,请进行除法运算:
| |
To convert an integer number of units to a Duration, multiply:
要将整数单位转换为 Duration,请使用乘法:
| |
变量
This section is empty.
函数
func After
| |
After waits for the duration to elapse and then sends the current time on the returned channel. It is equivalent to NewTimer(d).C.
After 等待指定的持续时间过去,然后将当前时间发送到返回的通道上。它等价于 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.
在 Go 1.23 之前,这段文档警告说,底层的 Timer 在触发前不会被垃圾回收器回收,如果效率是一个问题,代码应该使用 NewTimer 并在计时器不再需要时调用 Timer.Stop。从 Go 1.23 开始,垃圾回收器可以回收未被引用且未停止的计时器。因此,当 After 可以满足需求时,没有理由偏向 NewTimer。
After Example(go1.23.0之前)
| |
After Example(go1.23.0开始)
| |
func Sleep
| |
Sleep pauses the current goroutine for at least the duration d. A negative or zero duration causes Sleep to return immediately.
Sleep函数暂停当前 goroutine 至少持续时间 d。负或零持续时间会使 Sleep 立即返回。
Sleep Example
| |
func Tick
| |
Tick is a convenience wrapper for NewTicker providing access to the ticking channel only. Unlike NewTicker, Tick will return nil if d <= 0.
Tick 是 NewTicker 的便捷包装,只提供对滴答通道的访问。如果 d <= 0,与 NewTicker 不同,Tick 会返回 nil。
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.
在 Go 1.23 之前,这段文档警告说,底层的 Ticker 永远不会被垃圾回收器回收,如果效率是一个问题,代码应该使用 NewTicker 并在计时器不再需要时调用 Ticker.Stop。从 Go 1.23 开始,垃圾回收器可以回收未被引用的滴答计时器,即使它们尚未停止。因此,当 Tick 可以满足需求时,不再需要通过调用 Stop 来帮助垃圾回收器,也没有理由偏向 NewTicker。
Tick Example
| |
| |
类型
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.
Duration类型表示两个时间点之间经过的时间,以 int64 纳秒计数的方式表示。该表示方式将最大可表示的持续时间限制在大约 290 年左右。
Example
| |
func ParseDuration
| |
ParseDuration parses a duration string. A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as “300ms”, “-1.5h” or “2h45m”. Valid time units are “ns”, “us” (or “µs”), “ms”, “s”, “m”, “h”.
ParseDuration 函数解析一个持续时间字符串。持续时间字符串是一个可能带有符号的十进制数序列,每个数字都可以有小数部分和单位后缀,例如 “300ms”、"-1.5h” 或 “2h45m”。有效的时间单位有 “ns”、“us”(或 “µs”)、“ms”、“s”、“m” 和 “h”。
ParseDuration Example
| |
func Since
| |
Since returns the time elapsed since t. It is shorthand for time.Now().Sub(t).
Since 函数返回自 t 以来经过的时间。它相当于 time.Now().Sub(t)。
func Until <- go1.8
| |
Until returns the duration until t. It is shorthand for t.Sub(time.Now()).
Until 函数返回直到 t 的时间间隔。它相当于 t.Sub(time.Now())。
(Duration) Abs <- go1.19
| |
Abs returns the absolute value of d. As a special case, math.MinInt64 is converted to math.MaxInt64.
Abs方法返回 d 的绝对值。作为特殊情况,将 math.MinInt64 转换为 math.MaxInt64。
(Duration) Hours
| |
Hours returns the duration as a floating point number of hours.
Hours 方法返回持续时间作为小时数的浮点数。
Hours Example
| |
(Duration) Microseconds <- go1.13
| |
Microseconds returns the duration as an integer microsecond count.
Microseconds方法返回以整数微秒计算的持续时间。
Microseconds Example
| |
(Duration) Milliseconds <- go1.13
| |
Milliseconds returns the duration as an integer millisecond count.
Milliseconds方法返回以整数毫秒计算的持续时间。
Milliseconds Example
| |
(Duration) Minutes
| |
Minutes returns the duration as a floating point number of minutes.
Minutes方法返回浮点数表示的分钟数持续时间。
Minutes Example
| |
(Duration) Nanoseconds
| |
Nanoseconds returns the duration as an integer nanosecond count.
Nanoseconds方法返回以整数纳秒计算的持续时间。
Nanoseconds Example
| |
(Duration) Round <- go1.9
| |
Round returns the result of rounding d to the nearest multiple of m. The rounding behavior for halfway values is to round away from zero. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, Round returns the maximum (or minimum) duration. If m <= 0, Round returns d unchanged.
Round方法返回将d四舍五入为m的最近倍数的结果。如果结果超过可以存储在Duration中的最大(或最小)值,则Round返回最大(或最小)持续时间。如果m<=0,则Round返回未更改的d。
Round Example
| |
(Duration) Seconds
| |
Seconds returns the duration as a floating point number of seconds.
Seconds方法返回浮点数表示的秒数持续时间。
Seconds Example
| |
(Duration) String
| |
String returns a string representing the duration in the form “72h3m0.5s”. Leading zero units are omitted. As a special case, durations less than one second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure that the leading digit is non-zero. The zero duration formats as 0s.
String方法以 “72h3m0.5s” 的形式返回持续时间的字符串表示形式。省略前导零的单位。作为特殊情况,持续时间小于一秒的格式使用更小的单位(毫秒、微秒或纳秒),以确保前导数字不为零。零持续时间格式化为0s。
String Example
| |
| |
(Duration) Truncate <- go1.9
| |
Truncate returns the result of rounding d toward zero to a multiple of m. If m <= 0, Truncate returns d unchanged.
Truncate方法将 d 向零舍入为 m 的倍数并返回结果。如果 m <= 0,则 Truncate 返回未经更改的 d。
Truncate Example
| |
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.
Location结构体将时间时刻映射到使用的时区。通常,Location 表示在地理区域中使用的时间偏移集合。对于许多 Location,时间偏移量取决于在时间时刻是否使用夏令时。
Example
| |
| |
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.
Local表示系统的本地时区。在 Unix 系统上,Local 会查询 TZ 环境变量以找到要使用的时区。没有 TZ 意味着使用系统默认值 /etc/localtime。TZ="" 表示使用 UTC。TZ=“foo” 表示使用系统时区目录中的文件 foo。
| |
UTC represents Universal Coordinated Time (UTC).
UTC 表示协调世界时 (UTC)。
func FixedZone
| |
FixedZone returns a Location that always uses the given zone name and offset (seconds east of UTC).
FixedZone函数返回始终使用给定区域名称和偏移量(相对于 UTC 的秒数)的 Location。
FixedZone Example
| |
func LoadLocation
| |
LoadLocation returns the Location with the given name.
LoadLocation函数返回具有给定名称的 Location。
If the name is "" or “UTC”, LoadLocation returns UTC. If the name is “Local”, LoadLocation returns Local.
如果名称为 "" 或 “UTC”,LoadLocation 返回 UTC。如果名称为 “Local”,LoadLocation 返回 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”.
否则,名称被视为对应于 IANA 时区数据库中的文件的位置名称,例如 “America/New_York”。
LoadLocation looks for the IANA Time Zone database in the following locations in order:
LoadLocation 按顺序在以下位置查找 IANA 时区数据库:
- the directory or uncompressed zip file named by the ZONEINFO environment variable
- 由 ZONEINFO 环境变量指定的目录或未压缩的 zip 文件
- on a Unix system, the system standard installation location
- 在 Unix 系统上,是系统标准安装位置
$GOROOT/lib/time/zoneinfo.zip- the time/tzdata package, if it was imported
- 如果导入了 time/tzdata 包,它将用于查找时区信息。
LoadLocation Example
| |
func LoadLocationFromTZData <- go1.10
| |
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).
LoadLocationFromTZData 函数从 IANA 时区数据库格式的数据中返回一个指定名字的 Location。该数据应该采用标准的 IANA 时区文件格式(例如,在 Unix 系统上的 /etc/localtime 内容)。
(*Location) String
| |
String returns a descriptive name for the time zone information, corresponding to the name argument to LoadLocation or FixedZone.
String 方法返回一个描述性的字符串,表示时区信息,对应于 LoadLocation 或 FixedZone 中的 name 参数。
type Month
| |
A Month specifies a month of the year (January = 1, …).
Month 类型表示一年中的月份(1 代表一月,……)。
Example
| |
| |
(Month) String
| |
String returns the English name of the month (“January”, “February”, …).
String 方法返回该月份的英文名称(“January”、“February” 等)。
type ParseError
| |
ParseError describes a problem parsing a time string.
ParseError 类型描述解析时间字符串时的问题。
(*ParseError) Error
| |
Error returns the string representation of a ParseError.
Error 方法返回 ParseError 的字符串表示形式。
type Ticker
| |
A Ticker holds a channel that delivers “ticks” of a clock at intervals.
Ticker 持有一个通道,该通道以时间间隔提供时钟"滴答声"。
func NewTicker
| |
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.
NewTicker 返回一个新的 Ticker,其中包含一个通道,该通道将在每次滴答后发送当前时间。滴答的周期由 d 参数指定。滴答器会调整时间间隔或丢弃滴答,以弥补接收速度慢的问题。d 必须大于零,否则 NewTicker 会触发 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.)
在 Go 1.23 之前,垃圾回收器不会回收尚未过期或未停止的滴答器,因此代码通常在调用 NewTicker 后立即使用 defer t.Stop 来确保滴答器在不再需要时可被回收。从 Go 1.23 开始,垃圾回收器可以回收未引用的滴答器,即使它们尚未停止。Stop 方法不再需要用来帮助垃圾回收器。(当然,代码仍可能需要调用 Stop 来出于其他原因停止滴答器。)
NewTicker Example
| |
(*Ticker) Reset <- go1.15
| |
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.
Reset方法停止一个 Ticker 并将其周期重置为指定的时间间隔。下一个 tick 将在新周期过去后到达。时间间隔d 必须大于零;否则,Reset 方法会 panic。
| |
(*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”.
Stop方法关闭一个 Ticker。Stop 后,将不会再发送任何 tick。Stop 不会关闭通道,以防止并发的 goroutine 从通道中读取到错误的"tick"。
type Time
| |
A Time represents an instant in time with nanosecond precision.
Time 表示带有纳秒精度的时间点。
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.
使用时间的程序通常应将其存储和传递为值,而不是指针。也就是说,时间变量和结构字段应为 time.Time 类型,而不是 *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 值可以被多个 goroutine 同时使用,除了 GobDecode、UnmarshalBinary、UnmarshalJSON 和 UnmarshalText 方法之外。这些方法不支持并发安全性。
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.
时间点可以使用 Before、After 和 Equal 方法进行比较。Sub 方法减去两个时间点,产生一个 Duration。Add 方法将一个时间点和一个 Duration 相加,产生一个时间点。
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.
Time 类型的零值是 UTC 时间的 1 年 1 月 1 日 00:00:00.000000000。由于实际使用中不太可能遇到这个时间,IsZero 方法提供了一种简单的方式来检测未明确初始化的时间。
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.
每个 Time 都有一个关联的 Location,在计算时间的表示形式时进行查询,例如在 Format、Hour 和 Year 方法中。Local、UTC 和 In 方法返回具有特定位置的时间。以这种方式更改位置只更改表示形式;它不会更改所表示的时间点,因此不会影响前面段落中描述的计算。
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.
一个保存了 GobEncode,MarshalBinary,MarshalJSON 和 MarshalText 方法的 Time 值的表示形式存储了 Time.Location 的偏移量,但没有存储位置名称,因此它们会丢失关于夏令时的信息。
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.
除了必须的"挂钟"读数之外,一个 Time 可能还包含当前进程单调钟的可选读数,以提供比较或减法的额外精度。有关详细信息,请参见包文档中的"单调钟"部分。
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.
请注意,Go 的 == 操作符不仅比较时间瞬间,还比较 Location 和单调钟读数。因此,在未保证所有值都已设置相同的 Location 之前,不应将 Time 值用作映射或数据库键,可以通过使用 UTC 或 Local 方法来实现,同时剥离单调钟读数,设置 t = t.Round(0)。通常,优先使用 t.Equal(u) 而不是 t == u,因为 t.Equal 使用可用的最准确的比较,并正确处理仅有一个参数具有单调钟读数的情况。
func Date
| |
Date returns the Time corresponding to yyyy-mm-dd hh:mm:ss + nsec nanoseconds in the appropriate zone for that time in the given location.
Date函数返回与给定位置中该时间的适当区域内的"yyyy-mm-dd hh:mm:ss + nsec nanoseconds"相对应的 Time。
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.
月份,日期,小时,分钟,秒和纳秒的值可能超出其通常范围,并在转换期间进行归一化。例如,10 月 32 日转换为 11 月 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.
夏令时转换会跳过或重复时间。例如,在美国,2011 年 3 月 13 日 2:15 上午从未发生过,而在 2011 年 11 月 6 日 1:15 上午则发生了两次。在这种情况下,时区和因此时间的选择并不明确。Date 返回一个在转换涉及的两个区域中一个区域内正确的时间,但不保证是哪一个。
Date panics if loc is nil.
如果 loc 为 nil,Date 将 panic。
Date Example
| |
func Now
| |
Now returns the current local time.
Now函数返回当前本地时间。
func Parse
| |
Parse parses a formatted string and returns the time value it represents. See the documentation for the constant called Layout to see how to represent the format. The second argument must be parseable using the format string (layout) provided as the first argument.
Parse函数解析格式化的字符串并返回其代表的时间值。查看名为 Layout 的常量的文档以了解如何表示格式。第二个参数必须可用作第一个参数提供的格式字符串(layout)进行解析。
The example for Time.Format demonstrates the working of the layout string in detail and is a good reference.
Time.Format 的示例详细演示了布局字符串的工作原理,并且是一个很好的参考。
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.
布局中省略的元素被假定为零或(当零不可能时)为一,因此解析"3:04pm"会返回对应于 0 年 1 月 1 日 15:04:00 UTC 的时间(请注意,因为年份是 0,所以此时间在零时间之前)。年份必须在 0000..9999 范围内。星期几的语法被检查,但是被忽略。
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.
对于指定两位数年份 06 的布局,NN >= 69 的值将被视为 19NN,NN < 69 的值将被视为 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.
如果没有时区指示符,则 Parse 返回 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.
当解析具有类似于 -0700 的区域偏移量的时间时,如果该偏移量对应于当前位置(Local)使用的时区,则 Parse 使用该位置和区域在返回的时间中。否则,它会将时间记录为处于一个虚构的位置,该位置的时间固定在给定的区域偏移量上。
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.
当解析具有类似于 MST 的区域缩写的时间时,如果该区域缩写在当前位置具有定义的偏移量,则使用该偏移量。无论位置如何,“UTC"区域缩写都被认为是 UTC。如果区域缩写未知,则 Parse 记录该时间处于具有给定区域缩写和零偏移量的虚构位置。此选择意味着可以使用相同的布局无损地解析和重新格式化此类时间,但是表示中使用的确切时刻将与实际区域偏移量不同。为避免此类问题,请使用使用数字区域偏移量的时间布局,或使用 ParseInLocation。
Parse Example
| |
func ParseInLocation <- go1.1
| |
ParseInLocation is like Parse but differs in two important ways. First, in the absence of time zone information, Parse interprets a time as UTC; ParseInLocation interprets the time as in the given location. Second, when given a zone offset or abbreviation, Parse tries to match it against the Local location; ParseInLocation uses the given location.
ParseInLocation函数与Parse函数类似,但有两个重要区别。首先,在缺少时区信息的情况下,Parse将一个时间解释为UTC;而ParseInLocation则将时间解释为给定时区的时间。其次,当给定时区偏移量或缩写时,Parse会尝试将其与本地时区匹配;而ParseInLocation使用给定时区。
ParseInLocation Example
| |
func Unix
| |
Unix returns the local Time corresponding to the given Unix time, sec seconds and nsec nanoseconds since January 1, 1970 UTC. It is valid to pass nsec outside the range [0, 999999999]. Not all sec values have a corresponding time value. One such value is 1«63-1 (the largest int64 value).
Unix函数返回与自1970年1月1日UTC以来的sec秒和nsec纳秒对应的本地时间。传递nsec超出范围[0, 999999999]是有效的。并非所有的sec值都有相应的时间值。其中一个这样的值是1«63-1(最大的int64值)。
Unix Example
| |
func UnixMicro <- go1.17
| |
UnixMicro returns the local Time corresponding to the given Unix time, usec microseconds since January 1, 1970 UTC.
UnixMicro函数返回与自1970年1月1日UTC以来的usec微秒对应的本地时间。
UnixMicro Example
| |
func UnixMilli <- go1.17
| |
UnixMilli returns the local Time corresponding to the given Unix time, msec milliseconds since January 1, 1970 UTC.
UnixMilli函数返回与自1970年1月1日UTC以来的msec毫秒对应的本地时间。
UnixMilli Example
| |
(Time) Add
| |
Add returns the time t+d.
Add方法返回t+d时间。
Add Example
| |
(Time) AddDate
| |
AddDate returns the time corresponding to adding the given number of years, months, and days to t. For example, AddDate(-1, 2, 3) applied to January 1, 2011 returns March 4, 2010.
AddDate方法返回添加指定年、月、日后的时间 t。例如,将 AddDate(-1, 2, 3) 应用于 2011 年 1 月 1 日,会返回 2010 年 3 月 4 日。
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.
AddDate方法会像 Date 方法一样对其结果进行规范化,因此例如将 10 月 31 日加一月会得到规范化后的 11 月 31 日,即 12 月 1 日。
AddDate Example
| |
(Time) After
| |
After reports whether the time instant t is after u.
After方法报告时间点 t 是否在 u 之后。
After Example
| |
(Time) AppendBinary <- 1.24.0
| |
AppendBinary implements the encoding.BinaryAppender interface.
(Time) AppendFormat <- go1.5
| |
AppendFormat is like Format but appends the textual representation to b and returns the extended buffer.
AppendFormat方法与 Format方法类似,但将文本表示附加到 b 中并返回扩展缓冲区。
AppendFormat Example
| |
(Time) AppendText <- 1.24.0
| |
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.
(Time) Before
| |
Before reports whether the time instant t is before u.
Before方法报告时间点 t 是否在 u 之前。
Before Example
| |
(Time) Clock
| |
Clock returns the hour, minute, and second within the day specified by t.
Clock方法返回指定 t 的所在日的小时、分钟和秒。
(Time) Compare <- go1.20
| |
Compare compares the time instant t with u. If t is before u, it returns -1; if t is after u, it returns +1; if they’re the same, it returns 0.
Compare方法比较时间点 t 和 u。如果 t 在 u 之前,则返回 -1;如果 t 在 u 之后,则返回 +1;如果它们相同,则返回 0。
(Time) Date
| |
Date returns the year, month, and day in which t occurs.
Date方法返回 t 所代表的年、月、日。
Date Example
| |
(Time) Day
| |
Day returns the day of the month specified by t.
Day方法返回 t 所代表的月份中的第几天。
Day Example
| |
(Time) Equal
| |
Equal reports whether t and u represent the same time instant. Two times can be equal even if they are in different locations. For example, 6:00 +0200 and 4:00 UTC are Equal. See the documentation on the Time type for the pitfalls of using == with Time values; most code should use Equal instead.
Equal方法报告 t 和 u 是否代表同一时刻。即使两个时间处于不同的时区,它们也可以相等。例如,6:00 +0200 和 4:00 UTC 是相等的。有关使用 == 与 Time 值时遇到的问题,请参阅 Time 类型的文档;大多数代码应该使用 Equal。
Equal Example
| |
(Time) Format
| |
Format returns a textual representation of the time value formatted according to the layout defined by the argument. See the documentation for the constant called Layout to see how to represent the layout format.
Format方法根据提供的格式返回 t 的文本表示。有关如何表示布局格式的信息,请参阅名为 Layout 的常量的文档。
The executable example for Time.Format demonstrates the working of the layout string in detail and is a good reference.
Time.Format 的可执行示例详细演示了布局字符串的工作方式,是一个很好的参考。
Format Example
| |
Format Example(Pad)
| |
(Time) GoString <- go1.17
| |
GoString implements fmt.GoStringer and formats t to be printed in Go source code.
GoString方法实现了 fmt.GoStringer 接口,并将 t 格式化为可打印的 Go 源代码。
GoString Example
| |
(*Time) GobDecode
| |
GobDecode implements the gob.GobDecoder interface.
GobDecode方法实现了 gob.GobDecoder 接口。
(Time) GobEncode
| |
GobEncode implements the gob.GobEncoder interface.
GobEncode方法实现了 gob.GobEncoder 接口。
(Time) Hour
| |
Hour returns the hour within the day specified by t, in the range [0, 23].
Hour方法返回 t 所在的一天中的小时数,范围为 [0, 23]。
(Time) ISOWeek
| |
ISOWeek returns the ISO 8601 year and week number in which t occurs. Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 of year n+1.
ISOWeek方法返回 t 所在的 ISO 8601 年份和周数。周数从 1 到 53。一月 1 日到 3 日属于年 n 的第 52 或 53 周,而 12 月 29 日到 31 日可能属于年 n+1 的第 1 周。
(Time) In
| |
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方法返回表示与 t 相同时间点的副本,但将副本的位置信息设置为 loc 以供显示。
In panics if loc is nil.
如果 loc 为 nil,则会引发 panic。
(Time) IsDST <- go1.17
| |
IsDST reports whether the time in the configured location is in Daylight Savings Time.
IsDST方法报告配置位置中的时间是否处于夏令时。
(Time) IsZero
| |
IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.
IsZero方法报告t是否表示零时刻,即UTC时间的January 1, year 1, 00:00:00.
(Time) Local
| |
Local returns t with the location set to local time.
Local方法返回t对应的本地时间。
(Time) Location
| |
Location returns the time zone information associated with t.
Location方法返回t对应的时区信息。
(Time) MarshalBinary <- go1.2
| |
MarshalBinary implements the encoding.BinaryMarshaler interface.
MarshalBinary方法实现encoding.BinaryMarshaler接口。
(Time) MarshalJSON
| |
MarshalJSON implements the 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.
MarshalJSON方法实现json.Marshaler接口。时间使用带有亚秒精度的RFC 3339格式的带引号的字符串表示。如果时间戳无法表示为有效的RFC 3339格式(例如,年份超出范围),则报告错误。
(Time) MarshalText <- go1.2
| |
MarshalText implements the encoding.TextMarshaler 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 reported.
MarshalText方法实现encoding.TextMarshaler接口。时间使用带有亚秒精度的RFC 3339格式表示。如果时间戳无法表示为有效的RFC 3339格式(例如,年份超出范围),则报告错误。
(Time) Minute
| |
Minute returns the minute offset within the hour specified by t, in the range [0, 59].
Minute方法返回t对应的小时内分钟数,范围为[0, 59]。
(Time) Month
| |
Month returns the month of the year specified by t.
Month方法返回t对应的月份。
(Time) Nanosecond
| |
Nanosecond returns the nanosecond offset within the second specified by t, in the range [0, 999999999].
Nanosecond方法返回t对应的秒内纳秒数,范围为[0, 999999999]。
(Time) Round <- go1.1
| |
Round returns the result of rounding t to the nearest multiple of d (since the zero time). The rounding behavior for halfway values is to round up. If d <= 0, Round returns t stripped of any monotonic clock reading but otherwise unchanged.
Round方法返回将t四舍五入到离d的最近倍数后的结果(自零时间开始)。半数值的舍入行为为向上舍入。如果d<=0,则Round返回除单调钟读数以外其他方面都没有改变的t。
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.
Round方法以自零时间以来的绝对持续时间为基础操作时间;它不以时间的表现形式为基础。因此,Round(Hour)可能会返回具有非零分钟的时间,这取决于时间的Location。
Round Example
| |
(Time) Second
| |
Second returns the second offset within the minute specified by t, in the range [0, 59].
Second方法返回 t 所代表的时间的秒数偏移量,范围在 [0, 59] 之间。
(Time) String
| |
String returns the time formatted using the format string
"2006-01-02 15:04:05.999999999 -0700 MST"
If the time has a monotonic clock reading, the returned string includes a final field “m=±
String方法返回使用格式字符串 “2006-01-02 15:04:05.999999999 -0700 MST” 格式化的时间。如果时间具有单调钟读数,则返回的字符串包括最终字段 “m=±<value>",其中 value 是单调钟读数,格式化为十进制秒数。
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.
返回的字符串仅用于调试;对于稳定的序列化表示,使用 t.MarshalText、t.MarshalBinary 或带有显式格式字符串的 t.Format。
String Example
| |
(Time) Sub
| |
Sub returns the duration t-u. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, the maximum (or minimum) duration will be returned. To compute t-d for a duration d, use t.Add(-d).
Sub方法返回 t-u 的持续时间。如果结果超过可以存储在 Duration 中的最大(或最小)值,则将返回最大(或最小)持续时间。要计算 t-d 的持续时间 d,请使用 t.Add(-d)。
Sub Example
| |
(Time) Truncate <- go1.1
| |
Truncate returns the result of rounding t down to a multiple of d (since the zero time). If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged.
Truncate方法返回将 t 向下舍入为 d 的倍数的结果(自零时起)。如果 d <= 0,则 Truncate 返回 t 去除任何单调钟读数但其他不变。
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.
Truncate方法在绝对时间自零时以来的持续时间上操作;它不会操作时间的表现形式。因此,Truncate(Hour) 可能会返回带有非零分钟的时间,具体取决于时间的位置。
Truncate Example
| |
(Time) UTC
| |
UTC returns t with the location set to UTC.
UTC方法将位置设置为 UTC 并返回 t。
(Time) Unix
| |
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.
Unix方法返回 t 作为 Unix 时间,即自 1970 年 1 月 1 日 UTC 以来经过的秒数。结果不依赖于与t关联的位置。类 Unix 操作系统通常将时间记录为 32 位秒计数,但由于此方法返回 64 位值,因此对过去或未来数十亿年都有效。
Unix Example
| |
(Time) UnixMicro <- go1.17
| |
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.
UnixMicro方法将 t 表示为 Unix 时间,即自 1970 年 1 月 1 日 UTC 起经过的微秒数。如果 Unix 时间不能被 int64 表示(即在年份 -290307 之前或 294246 之后),则结果未定义。结果不取决于与 t 关联的位置。
(Time) UnixMilli <- go1.17
| |
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.
UnixMilli方法将 t 表示为 Unix 时间,即自 1970 年 1 月 1 日 UTC 起经过的毫秒数。如果 Unix 时间不能被 int64 表示(即在 1970 年之前或之后的 29.2 亿年),则结果未定义。结果不取决于与 t 关联的位置。
(Time) UnixNano
| |
UnixNano returns t as a Unix time, the number of nanoseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in nanoseconds cannot be represented by an int64 (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.
UnixNano方法将 t 表示为 Unix 时间,即自 1970 年 1 月 1 日 UTC 起经过的纳秒数。如果 Unix 时间不能被 int64 表示(即在 1678 年之前或 2262 年之后的日期),则结果未定义。请注意,这意味着在零时间上调用 UnixNano 的结果是未定义的。结果不取决于与 t 关联的位置。
(*Time) UnmarshalBinary <- go1.2
| |
UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
UnmarshalBinary方法实现了 encoding.BinaryUnmarshaler 接口。
(*Time) UnmarshalJSON
| |
UnmarshalJSON implements the json.Unmarshaler interface. The time must be a quoted string in the RFC 3339 format.
UnmarshalJSON方法实现了 json.Unmarshaler 接口。时间必须是RFC 3339 格式的引号字符串。
(*Time) UnmarshalText <- go1.2
| |
UnmarshalText implements the encoding.TextUnmarshaler interface. The time must be in the RFC 3339 format.
UnmarshalText方法实现了 encoding.TextUnmarshaler 接口。时间必须是 RFC 3339格式。
(Time) Weekday
| |
Weekday returns the day of the week specified by t.
Weekday方法返回 t 指定的星期几。
(Time) Year
| |
Year returns the year in which t occurs.
Year方法返回 t 所在的年份。
(Time) YearDay <- go1.1
| |
YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years, and [1,366] in leap years.
YearDay方法返回 t 指定的年份的天数,在非闰年中为 [1,365] 范围内的数,闰年中为 [1,366]。
(Time) Zone
| |
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.
Zone 方法计算 t 所在时区,返回时区的缩写名称(例如"CET”)和其相对于 UTC 的偏移量(以秒为单位)。
(Time) ZoneBounds <- go1.19
| |
ZoneBounds returns the bounds of the time zone in effect at time t. The zone begins at start and the next zone begins at end. If the zone begins at the beginning of time, start will be returned as a zero Time. If the zone goes on forever, end will be returned as a zero Time. The Location of the returned times will be the same as t.
ZoneBounds方法返回t时刻所在时区的起始时间和终止时间。该时区从start开始,下一个时区从end开始。如果该时区从时间开始时刻开始,则start将作为零值Time返回。如果时区一直持续下去,则end将作为零值Time返回。返回的时间Location与t相同。
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.
Timer类型表示单个事件。当Timer过期时,当前时间将发送到C通道,除非Timer是由AfterFunc创建的。Timer必须使用NewTimer或AfterFunc创建。
func AfterFunc
| |
AfterFunc waits for the duration to elapse and then calls f in its own goroutine. It returns a Timer that can be used to cancel the call using its Stop method.
AfterFunc函数等待持续时间过去,然后在其自己的goroutine中调用f。它返回一个Timer,可以使用它的Stop方法取消调用。
| |
func NewTimer
| |
NewTimer creates a new Timer that will send the current time on its channel after at least duration d.
NewTimer 创建一个新的 Timer,它将在至少 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.)
在 Go 1.23 之前,垃圾回收器不会回收尚未过期或未停止的计时器,因此代码通常在调用 NewTimer 后立即使用 defer t.Stop 来确保计时器在不再需要时可被回收。从 Go 1.23 开始,垃圾回收器可以回收未引用的计时器,即使它们尚未过期或停止。Stop 方法不再需要用来帮助垃圾回收器。(当然,代码仍可能需要调用 Stop 来出于其他原因停止计时器。)
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.
在 Go 1.23 之前,计时器关联的通道是异步的(缓冲,容量为 1),这意味着即使在 Timer.Stop 或 Timer.Reset 返回后,仍可能接收到过时的时间值。从 Go 1.23 开始,该通道变为同步的(无缓冲,容量为 0),消除了接收过时值的可能性。
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.
通过设置 GODEBUG 的 asynctimerchan=1 可以恢复 Go 1.23 之前的行为:当设置此选项时,未过期的计时器将不会被垃圾回收,且通道将具有缓冲容量。此设置可能在 Go 1.27 或更高版本中被移除。
NewTimer My Example
| |
(*Timer) Reset <- go1.1
| |
Reset changes the timer to expire after duration d. It returns true if the timer had been active, false if the timer had expired or been stopped.
Reset 将计时器修改为在 d 持续时间后过期。如果计时器仍在活动中,则返回 true,如果计时器已经过期或停止,则返回 false。
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.
对于使用 AfterFunc(d, f) 创建的基于函数的计时器,Reset 会重新安排 f 的运行时间,这种情况下 Reset 返回 true;或者重新安排 f 再次运行,这种情况下它返回 false。当 Reset 返回 false 时,Reset 不会等待之前的 f 完成,也不保证之后的 f 运行不会与之前的 f 并发运行。如果调用方需要知道之前的 f 是否已经完成,则必须与 f 进行显式协调。
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 [Stop] and explicitly drain the timer first. See the NewTimer documentation for more details.
对于使用 NewTimer 创建的基于通道的计时器,从 Go 1.23 开始,Reset 返回后,确保从 t.C 接收的任何值不会对应之前的计时器设置;如果程序尚未从 t.C 接收且计时器正在运行,则 Reset 保证返回 true。在 Go 1.23 之前,唯一安全的 Reset 使用方式是先调用 [Stop] 并明确清空计时器。更多详细信息请参阅 NewTimer 文档。
go1.23.0之前 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.
Reset方法将计时器更改为在持续时间d后到期。如果计时器处于活动状态,则返回true,如果计时器已过期或已停止,则返回false。For a Timer created with NewTimer, Reset should be invoked only on stopped or expired timers with drained channels.
对于使用NewTimer创建的计时器,Reset只应在已停止或已过期且通道已排空的情况下调用。
个人注释
Reset只应在(已停止)或(已过期且通道已排空)的情况下调用。
怎么判断计时器已停止?
调用Stop方法返回true,可以说明计时器已停止。
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:
如果程序已经从t.C接收到值,则已知该计时器已过期并且通道已排空,因此可以直接使用t.Reset。但是,如果程序尚未从t.C接收到值(即未排空),则必须停止该计时器,并且如果Stop报告该计时器在停止之前已过期,则必须显式排空通道。
1 2 3 4if !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.
请注意,正确使用Reset的返回值是不可能的,因为在清空通道和新计时器到期之间存在竞态条件。应如上所述始终在已停止或已到期的通道上调用Reset,以保持与现有程序的兼容性。返回值存在是为了保持与现有程序的兼容性。
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.
对于使用
AfterFunc(d, f)创建的计时器,Reset方法要么重新安排f的运行时间,此时Reset方法返回true,要么安排f再次运行,此时Reset方法返回false。当Reset方法返回false时,Reset方法既不等待之前的f完成再返回,也不能保证后续运行f的goroutine不与之前的同时运行。如果调用方需要知道之前的f执行是否完成,它必须与f进行显式的协调。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71package main import ( "fmt" "time" ) func main() { fmt.Printf("--------------------\n timer1 \n --------------------\n") fmt.Println("before:", time.Now()) timer1 := time.AfterFunc(5*time.Second, func() { fmt.Println("timer1 has been 5+ seconds and Now time is \n", time.Now()) }) time.Sleep(2 * time.Second) fmt.Println("had sleep 2 second:", time.Now()) // 应始终在已停止或到期的通道上调用Reset,以保持与现有程序的兼容性 if !timer1.Stop() { <-timer1.C } fmt.Println("reset:", time.Now()) fmt.Printf("Reset timer1 return %t\n", timer1.Reset(5*time.Second)) time.Sleep(10 * time.Second) fmt.Printf("--------------------\n timer2 \n --------------------\n") fmt.Println("before:", time.Now()) timer2 := time.NewTimer(5 * time.Second) time.Sleep(2 * time.Second) fmt.Println("had sleep 2 second:", time.Now()) if !timer2.Stop() { fmt.Println("执行Stop方法ing...") <-timer2.C fmt.Println("已执行了Stop方法") } fmt.Printf("Reset timer2 return %t\n", timer2.Reset(5*time.Second)) for { select { case _, ok := <-timer2.C: if ok { fmt.Println("timer2 has been 5+ seconds and Now time is \n", time.Now()) goto END } default: } } END: fmt.Println("END") } // 请编译后在执行,直接使用go run 可能结果会不同!!! // Output: //-------------------- //timer1 //-------------------- //before: 2023-10-22 18:21:18.6134724 +0800 CST m=+0.006476501 //had sleep 2 second: 2023-10-22 18:21:20.6517914 +0800 CST m=+2.044795501 //reset: 2023-10-22 18:21:20.6520226 +0800 CST m=+2.045026701 //Reset timer1 return false //timer1 has been 5+ seconds and Now time is //2023-10-22 18:21:25.6589852 +0800 CST m=+7.051989301 //-------------------- //timer2 //-------------------- //before: 2023-10-22 18:21:30.6569628 +0800 CST m=+12.049966901 //had sleep 2 second: 2023-10-22 18:21:32.6692213 +0800 CST m=+14.062225401 //Reset timer2 return false //timer2 has been 5+ seconds and Now time is //2023-10-22 18:21:37.6838445 +0800 CST m=+19.076848601 //END
(*Timer) Stop
| |
Stop prevents the Timer from firing. It returns true if the call stops the timer, false if the timer has already expired or been stopped.
Stop 防止 Timer 触发。如果调用成功停止计时器,则返回 true;如果计时器已经过期或已停止,则返回 false。
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.
对于使用 AfterFunc(d, f) 创建的基于函数的计时器,如果 t.Stop 返回 false,则表示计时器已经过期,函数 f 已经在其自己的 goroutine 中启动;Stop 不会在返回之前等待 f 完成。如果调用方需要知道 f 是否已经完成,则必须与 f 进行显式协调。
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.
对于使用 NewTimer(d) 创建的基于通道的计时器,从 Go 1.23 开始,在 Stop 返回后,从 t.C 接收的任何值保证会被阻塞,而不是接收在 Stop 之前的过时时间值;如果程序尚未从 t.C 接收且计时器正在运行,则 Stop 保证返回 true。在 Go 1.23 之前,唯一安全的 Stop 使用方式是在 Stop 返回 false 时插入一个额外的 <-t.C 来清空潜在的过时值。更多详细信息请参阅 NewTimer 文档。
go1.23.0之前
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.
Stop方法用于阻止计时器触发。如果该调用成功停止了计时器,则返回true;如果计时器已过期或已停止,则返回false。Stop方法不会关闭通道,以防止从通道中成功读取不正确的数据。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:
为了确保在调用
Stop方法后通道为空,需要检查返回值并排空通道。例如,假设程序尚未从t.C接收到数据:
1 2 3if !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.
这不能与从该计时器的通道或其他对该计时器的Stop方法的调用并发执行。
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.
对于使用
AfterFunc(d, f)创建的计时器,如果t.Stop返回false,则计时器已过期,并且函数f已经在其自己的goroutine中启动;Stop方法在返回之前不会等待f完成。如果调用者需要知道f是否完成,它必须与f显式协调。
type Weekday
| |
A Weekday specifies a day of the week (Sunday = 0, …).
Weekday类型指定一周中的某一天(星期日= 0,…)。
| |
(Weekday) String
| |
String returns the English name of the day (“Sunday”, “Monday”, …).
String方法返回一周中指定的星期几的英文名称(“Sunday”、“Monday”,等等)。
| |