Go 语言的日期时间操作(二)
1. 格式化
Go 语言中日期和时间的格式化使用模式化方法 time.Format()来实现,它的签名如下:
func (t Time) Format(layout string) string
layout 参数定义了格式化的模板,模板里面的时间必须是 2006-01-02 15:04:05 这个时间,这个时间是固定的,不然就会出错。
2. 解析
Go 语言中日期和时间的解析使用模式化方法 time.Parse()来实现,它的签名如下:
func Parse(layout, value string) (Time, error)
layout 参数定义了格式化的模板,模板里面的时间必须是 2006-01-02 15:04:05 这个时间,这个时间是固定的,不然就会出错。
3. 时区
Go 语言中通过 time.LoadLocation()函数加载时区信息,该函数的签名如下:
func LoadLocation(name string) (*Location, error)
name 参数可以是 "Local"、"UTC",也可以是 IANA 时区数据库中的名字,比如 "America/New_York"。
4. 时间戳
时间戳是自 1970 年 1 月 1 日(08:00:00GMT)至当前时间的总毫秒数。它也被称为 Unix 时间戳(UnixTimestamp)。
func (t Time) Unix() int64
5. 时间操作
5.1. 获取时间戳
func (t Time) Unix() int64
5.2. 获取当前时间
func Now() Time
5.3. 获取年月日、时分秒
func (t Time) Year() int
func (t Time) Month() Month
func (t Time) Day() int
func (t Time) Hour() int
func (t Time) Minute() int
func (t Time) Second() int
5.4. 获取星期几
func (t Time) Weekday() Weekday
5.5. 获取一年中的第几天
func (t Time) YearDay() int
5.6. 时间比较
func (t Time) Before(u Time) bool
func (t Time) After(u Time) bool
func (t Time) Equal(u Time) bool
5.7. 时间加减
func (t Time) Add(d Duration) Time
func (t Time) AddDate(years int, months int, days int) Time
func (t Time) Sub(u Time) Duration
5.8. 定时器的应用
定时器的本质是一个通道(channel),定时器会在指定时间发送一个信号给通道,导致通道阻塞。
func After(d Duration) <-chan Time
func Sleep(d Duration)
package main
import (
"fmt"
"time"
)
func main() {
// 定义一个定时器,2秒后触发
timer := time.NewTimer(2 * time.Second)
now := time.Now()
fmt.Printf("now: %v\n", now)
// 2秒后,往timer通道里写数据,有数据后,就可以读取
t := <-timer.C
fmt.Printf("t: %v\n", t)
}
package main
import (
"fmt"
"time"
)
func main() {
// 定义一个定时器,2秒后触发
timer := time.NewTimer(2 * time.Second)
now := time.Now()
fmt.Printf("now: %v\n", now)
// 2秒后,往timer通道里写数据,有数据后,就可以读取
t := <-timer.C
fmt.Printf("t: %v\n", t)
// 重新设置定时器
timer.Reset(1 * time.Second)
t = <-timer.C
fmt.Printf("t: %v\n", t)
}
package main
import (
"fmt"
"time"
)
func main() {
// 定义一个定时器,2秒后触发
timer := time.NewTimer(2 * time.Second)
now := time.Now()
fmt.Printf("now: %v\n", now)
// 2秒后,往timer通道里写数据,有数据后,就可以读取
t := <-timer.C
fmt.Printf("t: %v\n", t)
// 重新设置定时器
timer.Reset(1 * time.Second)
t = <-timer.C
fmt.Printf("t: %v\n", t)
// 停止定时器
timer.Stop()
t = <-timer.C
fmt.Printf("t: %v\n", t)
}
5.9. 打点器的应用
打点器的本质是一个通道(channel),打点器会以一个恒定的时间间隔往通道发送一个事件(当前时间)。
func NewTicker(d Duration) *Ticker
func (t *Ticker) Stop()
package main
import (
"fmt"
"time"
)
func main() {
// 定义一个打点器,每500毫秒触发一次
ticker := time.NewTicker(time.Millisecond * 500)
// 创建一个计时器,设置为2秒,2秒后,停止打点器
stopper := time.NewTimer(time.Second * 2)
// 声明计数变量
var i int
// 不断地检查通道情况
for {
// 多路复用通道
select {
case <-stopper.C:
// 2秒后,停止
fmt.Println("stop")
// 跳出循环
goto StopHere
case <-ticker.C:
// 打点器触发了
i++
fmt.Println("tick", i)
}
}