目录 搜索
archive archive/tar archive/zip bufio bufio(缓存) builtin builtin(内置包) bytes bytes(包字节) compress compress/bzip2(压缩/bzip2) compress/flate(压缩/flate) compress/gzip(压缩/gzip) compress/lzw(压缩/lzw) compress/zlib(压缩/zlib) container container/heap(容器数据结构heap) container/list(容器数据结构list) container/ring(容器数据结构ring) context context(上下文) crypto crypto(加密) crypto/aes(加密/aes) crypto/cipher(加密/cipher) crypto/des(加密/des) crypto/dsa(加密/dsa) crypto/ecdsa(加密/ecdsa) crypto/elliptic(加密/elliptic) crypto/hmac(加密/hmac) crypto/md5(加密/md5) crypto/rand(加密/rand) crypto/rc4(加密/rc4) crypto/rsa(加密/rsa) crypto/sha1(加密/sha1) crypto/sha256(加密/sha256) crypto/sha512(加密/sha512) crypto/subtle(加密/subtle) crypto/tls(加密/tls) crypto/x509(加密/x509) crypto/x509/pkix(加密/x509/pkix) database database/sql(数据库/sql) database/sql/driver(数据库/sql/driver) debug debug/dwarf(调试/dwarf) debug/elf(调试/elf) debug/gosym(调试/gosym) debug/macho(调试/macho) debug/pe(调试/pe) debug/plan9obj(调试/plan9obj) encoding encoding(编码) encoding/ascii85(编码/ascii85) encoding/asn1(编码/asn1) encoding/base32(编码/base32) encoding/base64(编码/base64) encoding/binary(编码/binary) encoding/csv(编码/csv) encoding/gob(编码/gob) encoding/hex(编码/hex) encoding/json(编码/json) encoding/pem(编码/pem) encoding/xml(编码/xml) errors errors(错误) expvar expvar flag flag(命令行参数解析flag包) fmt fmt go go/ast(抽象语法树) go/build go/constant(常量) go/doc(文档) go/format(格式) go/importer go/parser go/printer go/scanner(扫描仪) go/token(令牌) go/types(类型) hash hash(散列) hash/adler32 hash/crc32 hash/crc64 hash/fnv html html html/template(模板) image image(图像) image/color(颜色) image/color/palette(调色板) image/draw(绘图) image/gif image/jpeg image/png index index/suffixarray io io io/ioutil log log log/syslog(日志系统) math math math/big math/big math/bits math/bits math/cmplx math/cmplx math/rand math/rand mime mime mime/multipart(多部分) mime/quotedprintable net net net/http net/http net/http/cgi net/http/cookiejar net/http/fcgi net/http/httptest net/http/httptrace net/http/httputil net/http/internal net/http/pprof net/mail net/mail net/rpc net/rpc net/rpc/jsonrpc net/smtp net/smtp net/textproto net/textproto net/url net/url os os os/exec os/signal os/user path path path/filepath(文件路径) plugin plugin(插件) reflect reflect(反射) regexp regexp(正则表达式) regexp/syntax runtime runtime(运行时) runtime/debug(调试) runtime/internal/sys runtime/pprof runtime/race(竞争) runtime/trace(执行追踪器) sort sort(排序算法) strconv strconv(转换) strings strings(字符串) sync sync(同步) sync/atomic(原子操作) syscall syscall(系统调用) testing testing(测试) testing/iotest testing/quick text text/scanner(扫描文本) text/tabwriter text/template(定义模板) text/template/parse time time(时间戳) unicode unicode unicode/utf16 unicode/utf8 unsafe unsafe
文字

  • import "time"

  • 概观

  • 索引

  • 示例

概观

打包时间提供了测量和显示时间的功能。

日历计算总是假定公历,没有闰秒。

单调时钟

操作系统提供了一个“挂钟”,它可能会随时钟同步发生变化,而“单调时钟”则不会。一般的规则是挂钟是用来告诉时间的,而单调时钟是用来测量时间的。Time.Now 包含挂钟读数和单调时钟读数,而不是拆分 API,在此包装中, time.Now 返回时间。后来的讲时间操作使用挂钟读数,但后来的时间测量操作,特别是比较和减法,使用单调时钟读数。

例如,即使挂钟在定时操作期间发生变化,该代码也会计算大约20毫秒的积极运行时间:

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

其他成语,如 time.Since(开始), time.Until(截止日期) 和 time.Now() 。之前(截止日期)对墙壁时钟重置具有类似的鲁棒性。

本节的其余部分给出了操作如何使用单调时钟的精确细节,但理解这些细节并不需要使用该包。

Time.Now 包含单调时钟读数。如果时间 t 具有单调时钟读数,则 t.Add 将相同的持续时间添加到挂钟和单调时钟读数以计算结果。因为 t.AddDate(y, m, d) ,t.Round(d),和t.Truncate(d) 是运行时间计算,他们总是剥去任何单调时钟从它们的结果读出。因为 t.In,t.Local 和 t.UTC 被用于解释壁挂时间的效果,所以它们也从其结果中去除任何单调的时钟读数。去除单调时钟读数的典型方法是使用 t = t.Round(0)。

如果 Times t 和 u 都包含单调时钟读数,则单独使用单调时钟读数来执行操作 t.After(u), t.Before(u), t.Equal(u), and t.Sub(u) ,忽略运行时间读数。如果 t 或 u 不包含单调时钟读数,这些操作将回落到使用挂钟读数。

由于单调时钟读取在当前进程之外没有任何意义,因此由 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 总是创建没有单调时钟读取的时间。

请注意,Go == 运算符不仅比较时间,还比较位置和单调时钟读数。有关时间值相等性测试的讨论,请参阅时间类型的文档。

对于调试, t.String 的结果确实包含单调时钟读数(如果存在)。如果由于不同的单调时钟读数而导致 t!= u,那么在打印 t.String() 和 u.String() 时将会看到这种差异。

索引

  • 常量

  • func After(d Duration) <-chan Time

  • func Sleep(d Duration)

  • func Tick(d Duration) <-chan Time

  • type Duration

  • func ParseDuration(s string) (Duration, error)

  • func Since(t Time) Duration

  • func Until(t Time) Duration

  • func (d Duration) Hours() float64

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

  • type Month

  • func (m Month) String() string

  • type ParseError

  • func (e *ParseError) Error() string

  • type Ticker

  • func NewTicker(d Duration) *Ticker

  • 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 (t Time) Add(d Duration) Time

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

  • func (t Time) After(u Time) bool

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

  • func (t Time) Before(u Time) bool

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

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

  • func (t Time) Day() int

  • func (t Time) Equal(u Time) bool

  • func (t Time) Format(layout string) string

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

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

  • func (t Time) Hour() int

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

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

  • func (t Time) IsZero() bool

  • func (t Time) Local() Time

  • func (t Time) Location() *Location

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

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

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

  • func (t Time) Minute() int

  • func (t Time) Month() Month

  • func (t Time) Nanosecond() int

  • func (t Time) Round(d Duration) Time

  • func (t Time) Second() int

  • func (t Time) String() string

  • func (t Time) Sub(u Time) Duration

  • func (t Time) Truncate(d Duration) Time

  • func (t Time) UTC() Time

  • func (t Time) Unix() int64

  • func (t Time) UnixNano() int64

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

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

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

  • func (t Time) Weekday() Weekday

  • func (t Time) Year() int

  • func (t Time) YearDay() int

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

  • type Timer

  • 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 (d Weekday) String() string

示例

在日期持续时间月份之后 Parse ParseInLocation Sleep Tick Time.Format Time.Round Time.Truncate

打包文件

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

常量

这些是在 Time.Format 和 Time.Parse 中使用的预定义布局。布局中使用的参考时间是特定时间:

Mon Jan 2 15:04:05 MST 2006

这是 Unix 时间 1136239445 。由于 MST 是 GMT-0700,参考时间可以被认为是

01/02 03:04:05PM '06 -0700

要定义自己的格式,请写下参考时间看起来像格式化的方式; 看例如 ANSIC,StampMicro 或 Kitchen 等常量的值。该模型将演示参考时间的样子,以便 Format 和 Parse 方法可以将相同的转换应用于一般时间值。

在格式字符串中,下划线_表示如果以下数字(一天)有两位数字,则可以用数字替换空格; 与固定宽度的 Unix 时间格式兼容。

小数点后跟一个或多个零表示小数秒,打印到给定的小数位数。小数点后跟一个或多个9表示小数秒,打印到给定的小数位数,删除尾随零。(仅)解析时,即使布局不表示它的存在,输入可能会在秒字段之后立即包含小数第二个字段。在这种情况下,小数点后跟最大的一系列数字将被解析为小数秒。

数字时区偏移格式如下:

-0700  ±hhmm-07:00 ±hh:mm-07    ±hh

使用 Z 替换格式中的符号会触发打印 Z 的 ISO 8601行 为,而不是 UTC 区域的偏移量。从而:

Z0700  Z or ±hhmm
Z07:00 Z or ±hh:mm
Z07    Z or ±hh

公认的星期几格式是"Mon" 和 "Monday"。公认的月份格式是"Jan" 和 "January"。

格式字符串中未被识别为参考时间一部分的文本在格式化过程中逐字回显,并且预期在输入中逐字显示为解析。

time.Format 的可执行示例详细说明了布局字符串的工作情况,并且是一个很好的参考。

请注意, RFC822,RFC850 和 RFC1123 格式应仅应用于当地时间。将它们应用于 UTC 时间将使用“UTC”作为时区缩写,而严格来说这些 RFC 在这种情况下需要使用“GMT”。对于坚持这种格式的服务器,通常应该使用 RFC1123Z 而不是 RFC1123Z ,而 RFC3339 应该是新协议的首选。 RFC822,RFC822Z,RFC1123 和 RFC1123Z 对格式化很有用;当与 time.Parse 一起使用时,它们不接受 RFC 允许的所有时间格式。RFC3339Nano 格式从秒字段中删除尾随零,因此格式化后可能无法正确排序。

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

func After

func After(d Duration) <-chan Time

在等待持续时间后,然后在返回的频道上发送当前时间。它相当于NewTimer(d).C。在定时器触发之前,底层 Timer 不会被垃圾收集器恢复。如果需要提高效率,请改用 NewTimer ,如果不再需要定时器,则调用 Timer.Stop。

示例

编码:

select {case m := <-c:        handle(m)case <-time.After(5 * time.Minute):
        fmt.Println("timed out")}

func Sleep

func Sleep(d Duration)

睡眠暂停当前的 goroutine 至少持续时间 d 。负值或零持续时间会导致 Sleep 立即返回。

示例

package mainimport ("time")func main() {
	time.Sleep(100 * time.Millisecond)}

func Tick

func Tick(d Duration) <-chan Time

Tick 是 NewTicker 的便捷包装,仅提供对滴答声频道的访问。虽然 Tick 对于不需要关闭 Ticker 的客户端非常有用,但请注意,如果没有办法关闭它,底层 Ticker 不能被垃圾收集器恢复; 它“泄漏”。与 NewTicker 不同,如果 d <= 0,Tick 将返回 nil。

示例

编码:

c := time.Tick(1 * time.Minute)for now := range c {
        fmt.Printf("%v %s\n", now, statusUpdate())}

type Duration

持续时间表示两个瞬间之间的经过时间,为int64纳秒计数。该表示将最大的可表示时间限制在约290年。

type Duration int64

常见的持续时间。对于 Day 或更大单位没有定义,以避免在夏令时时区转换时出现混淆。

要计算持续时间中的单位数量,请划分:

second := time.Second
fmt.Print(int64(second/time.Millisecond)) // prints 1000

要将整数个单位转换为持续时间,请乘以:

seconds := 10fmt.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)

码:

t0 := time.Now()expensiveCall()t1 := time.Now()fmt.Printf("The call took %v to run.\n", t1.Sub(t0))

func ParseDuration

func ParseDuration(s string) (Duration, error)

ParseDuration分析持续时间字符串。持续时间字符串是可能有符号的十进制数字序列,每个都有可选的分数和单位后缀,如“300ms”,“-1.5h”或“2h45m”。有效时间单位为“ns”,“us”(或“μs”),“ms”,“s”,“m”,“h”。

func Since

func Since(t Time) Duration

自从返回t以来的时间。它是time.Now()。Sub(t)的简写。

func Until

func Until(t Time) Duration

直到返回持续时间直到t。它是t.Sub(time.Now())的简写。

func (Duration) Hours

func (d Duration) Hours() float64

小时数将持续时间作为浮点小时数返回。

func (Duration) Minutes

func (d Duration) Minutes() float64

分钟将持续时间作为浮点分钟数返回。

func (Duration) Nanoseconds

func (d Duration) Nanoseconds() int64

纳秒将持续时间作为整数纳秒计数返回。

func (Duration) Round

func (d Duration) Round(m Duration) Duration

Round将舍入d的结果返回到m的最接近的倍数。中间值的舍入行为是从零开始舍入。如果结果超过了持续时间中可存储的最大(或最小)值,则返回最大(或最小)持续时间。如果m <= 0,则Round返回d不变。

func (Duration) Seconds

func (d Duration) Seconds() float64

秒将持续时间作为浮点秒数返回。

func (Duration) String

func (d Duration) String() string

字符串以“72h3m0.5s”的形式返回一个表示持续时间的字符串。前导零单位被忽略。作为一种特殊情况,小于一秒格式的持续时间使用较小的单位(毫秒,微秒或纳秒)以确保前导数字不为零。零持续时间格式为0。

func (Duration) Truncate

func (d Duration) Truncate(m Duration) Duration

截断返回四舍入d的结果为m的倍数。如果m <= 0,则截断返回d不变。

type Location

位置将时间映射到当时正在使用的区域。通常情况下,位置表示在某个地理区域使用的时间偏移量集合,例如中欧的CEST和CET。

type Location struct {        // contains filtered or unexported fields}

本地代表系统的本地时区。

var Local *Location = &localLoc

UTC代表全球协调时间(UTC)。

var UTC *Location = &utcLoc

func FixedZone

func FixedZone(name string, offset int) *Location

FixedZone返回一个始终使用给定区域名称和偏移量的位置(UTC以东的秒数)。

func LoadLocation

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

LoadLocation返回具有给定名称的位置。

如果名称是“”或“UTC”,则LoadLocation返回UTC。如果名称是“本地”,则LoadLocation返回本地。

否则,该名称将被视为与IANA时区数据库中的文件相对应的位置名称,例如“America / New_York”。

LoadLocation所需的时区数据库可能不存在于所有系统上,尤其是非Unix系统上。LoadLocation查找由ZONEINFO环境变量命名的目录或未压缩的zip文件(如果有),然后查看Unix系统上的已知安装位置,最后查看$ GOROOT / lib / time / zoneinfo.zip。

func (*Location) String

func (l *Location) String() string

字符串返回时区信息的描述性名称,对应于LoadLocation或FixedZone的名称参数。

type Month

一个月指定一年中的一个月份(1月= 1,...)。

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

示例

package mainimport ("fmt""time")func main() {
	_, month, day := time.Now().Date()if month == time.November && day == 10 {
		fmt.Println("Happy Go day!")}}

func (Month) String

func (m Month) String() string

字符串返回月份的英文名称 ("January", "February", ...)。

键入 ParseError

ParseError 描述解析时间字符串的问题。

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

func (*ParseError) Error

func (e *ParseError) Error() string

错误返回 ParseError 的字符串表示形式。

键入 代码

代码持有一个频道,每隔一段时间发送一个时钟的“嘀嗒”。

type Ticker struct {
        C <-chan Time // The channel on which the ticks are delivered.        // contains filtered or unexported fields}

func NewTicker

func NewTicker(d Duration) *Ticker

NewTicker 会返回一个新的 Ticker ,其中包含一个频道,该频道将使用持续时间参数指定的时间段发送时间。它会调整间隔或删除滴答以弥补慢速接收器。持续时间d必须大于零; 如果没有, NewTicker 会惊慌失措。停止代码以释放相关资源。

func (*Ticker) Stop

func (t *Ticker) Stop()

停止关闭代码。停止后,不会再发送任何蜱虫。停止不关闭通道,以防止从通道读取不正确的成功。

type Time

时间以纳秒精度表示即时。

使用时间的程序通常应该存储并传递它们作为值,而不是指针。也就是说,时间变量和结构字段的类型应该是 time.Time,而不是 * time.Time。

除了方法 GobDecode,UnmarshalBinary,UnmarshalJSON 和 UnmarshalText 不是并发安全的,一个 Time 值可以被多个 goroutine 同时使用。

时间点可以使用 Before,After 和 Equal 方法进行比较。Sub 方法减去两个瞬间,产生一个持续时间。Add 方法添加一个 Time 和一个 Duration,产生一个 Time。

时间类型的零值是 UTC 1月1日,1年,00:00:00.000000000。由于这个时间不太可能在实践中出现,IsZero 方法提供了一种简单的方法来检测未明确初始化的时间。

每个时间都与它关联一个位置,在计算时间表示形式(例如格式,小时和年份方法)时查阅。方法 Local,UTC 和 In 返回具有特定位置的时间。以这种方式更改位置只会改变演示文稿; 它不会改变所指示的时刻,因此不会影响前面段落中所述的计算。

请注意,Go == 运算符不仅比较时间,还比较位置和单调时钟读数。因此,如果不首先确保已为所有值设置了相同的位置(可通过使用UTC 或 Local 方法实现),并且单调时钟读数已被剥离,则不应将时间值用作地图或数据库密钥设置 t = t.Round(0) 。一般来说,首选 t.Equal(u) 而不是 t == u,因为 t.Equal 使用可用的最准确比较,并且只有其中一个参数具有单调时钟读数时才能正确处理这种情况。

除了所需的“挂钟”读数外,Time 还可以包含当前过程单调时钟的可选读数,以提供用于比较或减法的额外精度。有关详细信息,请参阅包装文档中的“单调时钟”部分。

type Time struct {        // contains filtered or unexported fields}

func Date

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

日期返回相应的时间

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

在给定位置的适当区域内。

月,日,小时,分钟,秒和 nsec 值可能超出其通常范围,并且在转换过程中将被归一化。例如,10月32日转换为11月1日。

夏令时转换跳过或重复次数。例如,在美国,2011年3月13日凌晨2点15分从未发生过,而2011年11月6日凌晨1点15分发生了两次。在这种情况下,时区的选择以及时间的选择并不明确。日期返回在转换中涉及的两个区域中的一个中正确的时间,但不能保证哪个时间。

如果 loc 为 nil ,日期中止。

示例

package mainimport ("fmt""time")func main() {
	t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
	fmt.Printf("Go launched at %s\n", t.Local())}

func Now

func Now() Time

现在返回当前的本地时间。

func Parse

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

解析解析格式化的字符串并返回它表示的时间值。布局通过显示如何定义参考时间来定义格式

Mon Jan 2 15:04:05 -0700 MST 2006

如果它是价值就会被解释;它作为输入格式的一个例子。然后对输入字符串进行相同的解释。

预定义的布局 ANSIC,UnixDate,RFC3339 等描述了标准和方便的参考时间表示。有关参考时间的格式和定义的更多信息,请参阅 ANSIC 文档以及由此包定义的其他常量。此外, time.Format 的可执行示例详细说明了布局字符串的工作情况,并且是一个很好的参考。

从值中省略的元素被假定为零,或者在0不可能时为1,因此解析“3:04 pm”将返回与UTC 1月1日,UTC 15:04:00对应的时间(请注意,由于年份是0,这个时间在零时间之前)。年数必须在0000到9999的范围内。检查星期几的语法,但忽略它。

在没有时区指示符的情况下,Parse 返回 UTC 时间。

当使用 -0700等区域偏移量解析时间时,如果偏移量与当前位置(本地)使用的时区相对应,则 Parse 会在返回的时间内使用该位置和区域。否则,它将时间记录在固定在给定区域偏移处的时间处于制造位置。

在使用区域缩写(如MST)解析时间时,如果区域缩写在当前位置中具有已定义的偏移量,则会使用该偏移量。无论位置如何,区域缩写“UTC”都被识别为 UTC。如果区域缩写未知,则 Parse 将时间记录为具有给定区域缩写和零偏移的制造位置。这种选择意味着这样一个时间可以无损地解析和重新格式化为相同的布局,但是在表示中使用的确切时刻会因实际的区域偏移而有所不同。为避免出现此类问题,请使用使用数字区域偏移量的时间布局,或使用 ParseInLocation。

示例

编码:

// See the example for time.Format for a thorough description of how// to define the layout string to parse a time.Time value; Parse and// Format use the same model to describe their input and output.// longForm shows by example how the reference time would be represented in// the desired layout.const longForm = "Jan 2, 2006 at 3:04pm (MST)"t, _ := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)")fmt.Println(t)// shortForm is another way the reference time would be represented// in the desired layout; it has no time zone present.// Note: without explicit zone, returns time in UTC.const shortForm = "2006-Jan-02"t, _ = time.Parse(shortForm, "2013-Feb-03")fmt.Println(t)

输出:

2013-02-03 19:54:00 -0800 PST2013-02-03 00:00:00 +0000 UTC

func ParseInLocation

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

ParseInLocation 类似于 Parse,但在两个重要方面有所不同。首先,在没有时区信息的情况下,Parse 将时间解释为 UTC;ParseInLocation 按照给定位置解释时间。其次,当给定区域偏移或缩写时,Parse 会尝试将其与本地位置进行匹配; ParseInLocation 使用给定的位置。

示例

编码:

loc, _ := time.LoadLocation("Europe/Berlin")const longForm = "Jan 2, 2006 at 3:04pm (MST)"t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)fmt.Println(t)// Note: without explicit zone, returns time in given location.const shortForm = "2006-Jan-02"t, _ = time.ParseInLocation(shortForm, "2012-Jul-09", loc)fmt.Println(t)

输出:

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

func Unix

func Unix(sec int64, nsec int64) Time

Unix 返回与给定的 Unix 时间相对应的本地时间,自1970年1月1日 UTC 以来秒数和纳秒。在范围0,999999999之外传递nsec是有效的。并非所有 sec 值都具有相应的时间值。一个这样的值是1 << 63-1(最大的int64值)。

func (Time) Add

func (t Time) Add(d Duration) Time

添加返回时间 t + d。

func (Time) AddDate

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

AddDate 返回相应于将给定年数,月份和天数添加到t的时间。例如,2011年1月1日应用的 AddDate(-1,2,3) 将返回2010年3月4日。

AddDate 使用与 Date 相同的方式对其结果进行规范化,因此,例如,在10月31日之前增加一个月会产生12月1日,即11月31日的规范化表单。

func (Time) After

func (t Time) After(u Time) bool

在报告时刻 t 是否在 u 之后。

func (Time) AppendFormat

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

AppendFormat 与 Format 相似,但将文本表示附加到 b 并返回扩展缓冲区。

func (Time) Before

func (t Time) Before(u Time) bool

在报告时刻 t 是否在你之前。

func (Time) Clock

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

时钟在 t 指定的日期内返回小时,分钟和秒。

func (Time) Date

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

日期返回出现 t 的年份,月份和日期。

func (Time) Day

func (t Time) Day() int

Day 返回由 t 指定的月份的一天。

func (Time) Equal

func (t Time) Equal(u Time) bool

Equal 报告 t 和 u 是否表示同一时刻。即使他们在不同的地点,两次也是平等的。例如,6:00 +0200 CEST和4:00 UTC 是 Equal。有关使用时间值 == 的缺陷,请参阅时间类型的文档; 大多数代码应该使用 Equal。

func (Time) Format

func (t Time) Format(layout string) string

格式返回按照布局格式化的时间值的文本表示,该格式通过显示如何定义参考时间来定义格式

Mon Jan 2 15:04:05 -0700 MST 2006

如果它是值,则会显示;它充当期望输出的一个例子。然后将相同的显示规则应用于时间值。

通过在布局字符串的秒部分的末尾添加句点和零来表示分数秒,如“15:04:05.000”中所示,以毫秒精度格式化时间戳。

预定义的布局ANSIC,UnixDate,RFC3339等描述了标准和方便的参考时间表示。有关参考时间的格式和定义的更多信息,请参阅 ANSIC 文档以及由此包定义的其他常量。

示例

package mainimport ("fmt""time")func main() {// Parse a time value from a string in the standard Unix format.
	t, err := time.Parse(time.UnixDate, "Sat Mar  7 11:06:39 PST 2015")if err != nil { // Always check errors even if they should not happen.panic(err)}// time.Time's Stringer method is useful without any format.
	fmt.Println("default format:", t)// Predefined constants in the package implement common layouts.
	fmt.Println("Unix format:", t.Format(time.UnixDate))// The time zone attached to the time value affects its output.
	fmt.Println("Same, in UTC:", t.UTC().Format(time.UnixDate))// The rest of this function demonstrates the properties of the// layout string used in the format.// The layout string used by the Parse function and Format method// shows by example how the reference time should be represented.// We stress that one must show how the reference time is formatted,// not a time of the user's choosing. Thus each layout string is a// representation of the time stamp,//	Jan 2 15:04:05 2006 MST// An easy way to remember this value is that it holds, when presented// in this order, the values (lined up with the elements above)://	  1 2  3  4  5    6  -7// There are some wrinkles illustrated below.// Most uses of Format and Parse use constant layout strings such as// the ones defined in this package, but the interface is flexible,// as these examples show.// Define a helper function to make the examples' output look nice.do := func(name, layout, want string) {
		got := t.Format(layout)if want != got {
			fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)return}
		fmt.Printf("%-15s %q gives %q\n", name, layout, got)}// Print a header in our output.
	fmt.Printf("\nFormats:\n\n")// A simple starter example.do("Basic", "Mon Jan 2 15:04:05 MST 2006", "Sat Mar 7 11:06:39 PST 2015")// For fixed-width printing of values, such as the date, that may be one or// two characters (7 vs. 07), use an _ instead of a space in the layout string.// Here we print just the day, which is 2 in our layout string and 7 in our// value.do("No pad", "<2>", "<7>")// An underscore represents a zero pad, if required.do("Spaces", "<_2>", "< 7>")// Similarly, a 0 indicates zero padding.do("Zeros", "<02>", "<07>")// If the value is already the right width, padding is not used.// For instance, the second (05 in the reference time) in our value is 39,// so it doesn't need padding, but the minutes (04, 06) does.do("Suppressed pad", "04:05", "06:39")// The predefined constant Unix uses an underscore to pad the day.// Compare with our simple starter example.do("Unix", time.UnixDate, "Sat Mar  7 11:06:39 PST 2015")// The hour of the reference time is 15, or 3PM. The layout can express// it either way, and since our value is the morning we should see it as// an AM time. We show both in one format string. Lower case too.do("AM/PM", "3PM==3pm==15h", "11AM==11am==11h")// When parsing, if the seconds value is followed by a decimal point// and some digits, that is taken as a fraction of a second even if// the layout string does not represent the fractional second.// Here we add a fractional second to our time value used above.
	t, err = time.Parse(time.UnixDate, "Sat Mar  7 11:06:39.1234 PST 2015")if err != nil {panic(err)}// It does not appear in the output if the layout string does not contain// a representation of the fractional second.do("No fraction", time.UnixDate, "Sat Mar  7 11:06:39 PST 2015")// Fractional seconds can be printed by adding a run of 0s or 9s after// a decimal point in the seconds value in the layout string.// If the layout digits are 0s, the fractional second is of the specified// width. Note that the output has a trailing zero.do("0s for fraction", "15:04:05.00000", "11:06:39.12340")// If the fraction in the layout is 9s, trailing zeros are dropped.do("9s for fraction", "15:04:05.99999999", "11:06:39.1234")}

func (*Time) GobDecode

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

GobDecode 实现了 gob.GobDecoder 接口。

func (Time) GobEncode

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

GobEncode 实现 gob.GobEncoder 接口。

func (Time) Hour

func (t Time) Hour() int

小时返回 t 指定的一天内的小时数,范围为0,23(0到23)。

func (Time) ISOWeek

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

ISOWeek 返回 t 发生的 ISO 8601 年和周数。周的范围为 1至53.n年的01月01日至03年1月03日可能属于n-1年的第52或53周,而12月29日至12月31日可能属于第 n + 1 年的第1周。

func (Time) In

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

在返回 t 时,位置信息设置为 loc。

在中止情况下,如果 loc 为 nil 。

func (Time) IsZero

func (t Time) IsZero() bool

IsZero 报告 t 是否表示 UTC 时间1月1日,1日00:00:00的零时刻。

func (Time) Local

func (t Time) Local() Time

本地返回 t ,其位置设置为当地时间。

func (Time) Location

func (t Time) Location() *Location

位置返回与 t 关联的时区信息。

func (Time) MarshalBinary

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

MarshalBinary 实现了 encoding.BinaryMarshaler 接口。

func (Time) MarshalJSON

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

MarshalJSON 实现了 json.Marshaler 接口。时间是以 RFC 3339 格式引用的字符串,如果存在,则添加亚秒精度。

func (Time) MarshalText

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

MarshalText 实现了 encoding.TextMarshaler 接口。时间格式为 RFC 3339 格式,如果存在,则会添加亚秒精度。

func (Time) Minute

func (t Time) Minute() int

分钟返回由 t 指定的小时内的分钟偏移量,范围为0,59(0到59)。

func (Time) Month

func (t Time) Month() Month

月返回由 t 指定的年份的月份。

func (Time) Nanosecond

func (t Time) Nanosecond() int

毫微秒返回由秒指定的秒内的纳秒偏移量,范围为0,999999999(0到999999999)。

func (Time) Round

func (t Time) Round(d Duration) Time

Round 将舍入 t 的结果返回到 d 的最近倍数(自零时间起)。中途值的舍入行为是四舍五入的。如果 d <= 0,Round 将返回t中的任何单调时钟读数,但不改变。

Round 在零时间之后作为绝对持续时间运行; 它不适用于当时的演示文稿格式。因此, Round(Hour) 可能会返回非零分钟的时间,具体取决于时间的位置。

示例

package mainimport ("fmt""time")func main() {
	t := time.Date(0, 0, 0, 12, 15, 30, 918273645, time.UTC)
	round := []time.Duration{
		time.Nanosecond,
		time.Microsecond,
		time.Millisecond,
		time.Second,2 * time.Second,
		time.Minute,10 * time.Minute,
		time.Hour,}for _, d := range round {
		fmt.Printf("t.Round(%6s) = %s\n", d, t.Round(d).Format("15:04:05.999999999"))}}

func (Time) Second

func (t Time) Second() int

第二个返回由 t 指定的分钟内的第二个偏移量,范围为0,59(0到59)。

func (Time) String

func (t Time) String() string

字符串返回使用格式字符串格式化的时间

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

如果时间具有单调时钟读数,则返回的字符串包含最终字段“m =±<value>”,其中 value 是单调时钟读数,格式为十进制秒数。

返回的字符串用于调试;对于稳定的序列化表示,请使用带明确格式字符串的 t.MarshalText,t.MarshalBinary 或 t.Format 。

func (Time) Sub

func (t Time) Sub(u Time) Duration

Sub 返回持续时间 t-u 。如果结果超过持续时间中可存储的最大(或最小)值,则会返回最大(或最小)持续时间。要计算持续时间 d 的 t-d,请使用 t.Add(-d)。

func (Time) Truncate

func (t Time) Truncate(d Duration) Time

截断将舍入 t 的结果返回到 d 的倍数(自零时间起)。如果 d <= 0,则截断返回除去任何单调时钟读数的 t ,否则不变。

截断操作时间为自零时间以来的绝对持续时间; 它不适用于当时的演示文稿格式。因此,根据时间的位置,截断(小时)可能会返回一个非零分钟的时间。

示例

编码:

t, _ := time.Parse("2006 Jan 02 15:04:05", "2012 Dec 07 12:15:30.918273645")trunc := []time.Duration{
        time.Nanosecond,
        time.Microsecond,
        time.Millisecond,
        time.Second,        2 * time.Second,
        time.Minute,        10 * time.Minute,}for _, d := range trunc {
        fmt.Printf("t.Truncate(%5s) = %s\n", d, t.Truncate(d).Format("15:04:05.999999999"))}// To round to the last midnight in the local timezone, create a new Date.midnight := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)_ = midnight

输出:

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

func (Time) UTC

func (t Time) UTC() Time

UTC 将位置设置为 UTC 时返回 t 。

func (Time) Unix

func (t Time) Unix() int64

Unix 将 t 作为 Unix 时间返回,即 UTC 自1970年1月1日以来经过的秒数。

func (Time) UnixNano

func (t Time) UnixNano() int64

UnixNano 返回 t 作为 Unix 时间,自 UTC  1970年1月1日起经过的纳秒数。如果 Unix 时间(纳秒)不能用 int64(1678年之前或2262之后的日期)表示,结果是不确定的。请注意,这意味着在零时间调用 UnixNano 的结果是未定义的。

func (*Time) UnmarshalBinary

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

UnmarshalBinary 实现了 encoding.BinaryUnmarshaler 接口。

func (*Time) UnmarshalJSON

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

UnmarshalJSON 实现了 json.Unmarshaler 接口。预计该时间是 RFC 3339 格式中的带引号的字符串。

func (*Time) UnmarshalText

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

UnmarshalText 实现了 encoding.TextUnmarshaler 接口。预计时间将采用 RFC 3339 格式。

func (Time) Weekday

func (t Time) Weekday() Weekday

平日返回由 t 指定的星期几。

func (Time) Year

func (t Time) Year() int

年份返回 t 发生的年份。

func (Time) YearDay

func (t Time) YearDay() int

YearDay 返回 t 指定的年份中的某一天,非闰年为 1,365,闰年为 1,366。

func (Time) Zone

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

Zone 计算在时间 t 有效的时区,并返回该区域的缩写名称(如“CET”)及其在 UTC 以东秒的偏移量。

type Timer

Timer 类型表示一个事件。当定时器到期时,当前时间将在 C 上发送,除非定时器是由 AfterFunc 创建的。定时器必须使用 NewTimer 或 AfterFunc 创建。

type Timer struct {
        C <-chan Time        // contains filtered or unexported fields}

func AfterFunc

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

AfterFunc 等待持续时间,然后在自己的 goroutine 中调用 f 。它返回一个 Timer ,它可以用来使用 Stop 方法取消调用。

func NewTimer

func NewTimer(d Duration) *Timer

NewTimer 创建一个新的定时器,在至少持续时间 d 后,它将在其通道上发送当前时间。

func (*Timer) Reset

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

重置更改定时器在持续时间 d 后过期。如果定时器处于活动状态,则返回 true ;如果定时器已到期或已停止,则返回 false 。

复位定时器必须注意不要与当前定时器到期时发送的 t.C 竞争。如果一个程序已经从 t.C 接收到一个值,定时器已知已经过期,并且 t.Reset 可以直接使用。但是,如果程序尚未从 t.C 接收到值,则必须停止定时器,并且——如果 Stop 在停止之前报告定时器已过期 ——则明确排空通道:

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

这不应该与来自定时器通道的其他接收同时完成。

请注意,无法正确使用重置的返回值,因为排出通道和新定时器到期之间存在争用情况。如上所述,应始终在已停止或已到期的渠道上调用重置。返回值的存在是为了保持与现有程序的兼容性。

func (*Timer) Stop

func (t *Timer) Stop() bool

停止防止定时器发射。如果调用停止定时器,则返回 true ;如果定时器已经过期或停止,则返回 false 。停止不关闭通道,以防止从通道读取不正确的成功。

为了防止在调用 Stop 之后使用 NewTimer 创建的定时器触发,请检查返回值并排空通道。例如,假设程序尚未从 t.C 收到:

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

这不能与来自定时器通道的其他接收同时完成。

对于使用 AfterFunc(d,f) 创建的定时器,如果 t.Stop 返回 false ,则定时器已经过期并且函数f已经在其自己的 goroutine 中启动;在返回之前停止不等待 f 完成。如果调用者需要知道f是否完成,则必须明确地与f协调。

键入 Weekday

星期几指定星期几(星期日= 0,...)。

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

func (Weekday) String

func (d Weekday) String() string

字符串返回当天的英文名称 ("Sunday", "Monday", ...) 。

上一篇: 下一篇: