time 用法大全
1.延迟d秒后返回通过信道返回时间值
func After(d Duration) <-chan Time
示例
package main import ( "time" "fmt" ) func main() { date := <- time.After(3*time.Second) fmt.Println(date) }
3 秒后会返回一个chan time 数据,程序继续向下执行
2.当前的 goroutine 睡眠至少持续时间d 如果d为0或者负值程序立即执行
func Sleep(d Duration)
package main import ( "time" "fmt" ) func main() { time.Sleep(1*time.Second) fmt.Println("延时1s执行") }
3. 不能被关闭的间隔触发器
func Tick(d Duration) <-chan Time
这个方法可以间隔的像信道填值,但是没有办法阻止这个过程
示例
package main import ( "time" "fmt" ) func main() { c := time.Tick(1 * time.Second) for now := range c { fmt.Printf("延时执行该做的事情 %s\n", now) } }
4.计算持续时间
type Duration int64
持续时间表示两个瞬间之间的经过时间,为int64纳秒计数。
package main import ( "time" "fmt" ) func main() { // 1s 等于 1000ms second := time.Second fmt.Println(int64(second/time.Millisecond)) // 10s seconds := 10 fmt.Println(time.Duration(seconds)*time.Second) }
5.将字符串解析成功时间格式
func ParseDuration(s string) (Duration, error)
有效时间单位为“ns”,“us”(或“μs”),“ms”,“s”,“m”,“h”
package main import ( "time" "fmt" ) func main() { d,error:= time.ParseDuration("2h2s") fmt.Println(d) fmt.Println(error) d,error = time.ParseDuration("2h2ns") fmt.Println(d) fmt.Println(error) d,error = time.ParseDuration("2s2ns") fmt.Println(d) fmt.Println(error) d,error = time.ParseDuration("2s2ms") fmt.Println(d) fmt.Println(error) }
6.计算从t到time.now 的时间
func Since(t Time) Duration
package main import ( "time" "fmt" ) func main() { // 将时间先转换成时间戳 s := time.Now().Local().UnixNano() // 已系统起始日期为基准计算偏移后的time t := time.Unix(0, s-1000000) // 与当前日期进行运算计算时间差 elapsed := time.Since(t) fmt.Println(elapsed) }
7.Until 从t计算到now的时间差
func Until(t Time) Duration
package main import ( "time" "fmt" ) func main() { // 将时间先转换成时间戳 s := time.Now().Local().UnixNano() // 已系统起始日期为基准计算偏移后的time t := time.Unix(0, s-1000000) // 与当前日期进行运算计算时间差 elapsed := time.Until(t) fmt.Println(elapsed) }
8.获取日期的年月日时分秒
func (t Time) Date() (year int, month Month, day int) func (t Time) Minute() int func (t Time) Month() Month func (t Time) Hour() int func (t Time) Day() int // 当月多少号 func (t Time) Weekday() Weekday func (t Time) Year() int func (t Time) YearDay() int func (t Time) Nanosecond() int func (t Time) Second() int
package main import ( "time" "fmt" ) func main() { // 将时间先转换成时间戳 t := time.Now() year := t.Year() month := t.Month() day := t.Day() h:= t.Hour() m:= t.Minute() s := t.Second() fmt.Printf("%d-%d-%d %d:%d:%d",year,month,day,h,m,s) }
9.计算总计多少小时,分钟 等
func (d Duration) Hours() float64 func (d Duration) Minutes() float64 func (d Duration) Nanoseconds() int64 func (d Duration) Seconds() float64
package main import ( "time" "fmt" ) func main() { // 将时间先转换成时间戳 now:= time.Now() t := now.Add(time.Second*3600) d := time.Until(t) fmt.Printf("共小时:%f\n",d.Hours()) fmt.Printf("共分钟:%f\n",d.Minutes()) fmt.Printf("共秒:%f\n",d.Seconds()) fmt.Printf("共纳秒:%d\n",d.Nanoseconds()) }
10. 将四舍五入d的结果值
func (d Duration) Round(m Duration) Duration
该时间点应该满足从Time零值到该时间点的时间段能整除d;如果有两个满足要求的时间点,距离t相同,会向上舍入;如果d <= 0,会返回t的拷贝
通俗的将,就是讲时间保留到指定的时间单位上如 t.Round(time.Second) 则最终的格式为 12:15:31
package main import ( "time" "fmt" ) 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")) } }
11.但是返回的是最接近但早于t的时间点
func (d Duration) Truncate(m Duration) Duration
package main import ( "time" "fmt" ) func main() { 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, time.Hour, } for _, d := range trunc { fmt.Printf("t.Truncate(%6s) = %s\n", d, t.Truncate(d).Format("15:04:05.999999999")) } }
12.返回格式化时间的字符串
func (d Duration) String() string
package main import ( "time" "fmt" ) func main() { t:=time.Now() fmt.Println(t.String()) }
13.获取当前日期
func Now() Time
package main import ( "time" "fmt" ) func main() { fmt.Println(time.Now()) }
14.增加日期的偏移量
func (t Time) Add(d Duration) Time
package main import ( "time" "fmt" ) func main() { tody := time.Now() tomorrow := tody.Add(time.Hour*24) fmt.Println(tody) fmt.Println(tomorrow) }
15.判断日期是否在日期u之前
func (t Time) Before(u Time) bool
package main import ( "time" "fmt" ) func main() { tody := time.Now() tomorrow := tody.Add(time.Hour*24) fmt.Println(tody.Before(tomorrow)) }
16.判断日期是否在日期u之前
func (t Time) After(u Time) bool
package main import ( "time" "fmt" ) func main() { tody := time.Now() tomorrow := tody.Add(time.Hour*24) fmt.Println(tody.After(tomorrow)) }
17.在当前日期上增加年月日的偏移量
func (t Time) AddDate(years int, months int, days int) Time
package main import ( "time" "fmt" ) func main() { tody := time.Now() fmt.Println(tody) fmt.Println(tody.AddDate(1,1,1)) }
18.获取时分秒
func (t Time) Clock() (hour, min, sec int)
package main import ( "time" "fmt" ) func main() { tody := time.Now() h,m,s := tody.Clock() fmt.Printf("%d:%d:%d",h,m,s) }
19.计算当前时间到指定时间的时间差
func (t Time) Sub(u Time) Duration
package main import ( "time" "fmt" ) func main() { today := time.Now() tomorrow := today.Add(time.Hour * 12) d := today.Sub(tomorrow) fmt.Println(d.Hours()) }
获取时间戳
func (t Time) Unix() int64 func (t Time) UnixNano() int64
示例
package main import ( "time" "fmt" ) func main() { today := time.Now() // 返回时间戳 单位s fmt.Println(today.Unix()) // 返回时间戳 单位纳秒 fmt.Println(today.UnixNano()) }
20.判断两个日期是否相等
func (t Time) Equal(u Time) bool
package main import ( "time" "fmt" ) func main() { today := time.Now() fmt.Println(today.Equal(today)) }
21.获取零时区的日期
func (t Time) UTC() Time
package main import ( "time" "fmt" ) func main() { today := time.Now() fmt.Println(today) fmt.Println(today.UTC()) }
22.计算当前时区和零时区之间的偏移量
func (t Time) Zone() (name string, offset int)
Zone计算t所在的时区,返回该时区的规范名(如"CET")和该时区相对于UTC的时间偏移量(单位秒)
package main import ( "time" "fmt" ) func main() { today := time.Now() name,offset := today.Zone() fmt.Println(name) fmt.Println(offset/3600) }
时差八个小时
23. 返回采用本地和本地时区
func (t Time) Local() Time
package main import ( "time" "fmt" ) func main() { today := time.Now() local := today.Local() fmt.Println(today) fmt.Println(local) }
24.获取指定时区的日期
func (t Time) In(loc *Location) Time
package main import ( "time" "fmt" ) func main() { loc,_:= time.LoadLocation("UTC") today := time.Now() todayUTC := today.In(loc) fmt.Println(loc) fmt.Println(today) fmt.Println(todayUTC) }
25.通过年月日时分秒时区创建日期
func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
示例
package main import ( "time" "fmt" ) func main() { loc,_:=time.LoadLocation("UTC") date := time.Date(2018,5,12,12,8,0,12,loc) fmt.Println(date) }
26.获取当前日期是当年的多少第几周
![image.png](http://upload-images.jianshu.io/upload_images/1594482-ed4acdaa971be2cc?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
返回时间点t对应的ISO 9601标准下的年份和星期编号。星期编号范围[1,53],1月1号到1月3号可能属于上一年的最后一周,12月29号到12月31号可能属于下一年的第一周。
示例
package main import ( "time" "fmt" ) func main() { now:=time.Now() year,week := now.ISOWeek() fmt.Println(year) fmt.Println(week) }
27.日期是不是零值
January 1, year 1, 00:00:00 UTC
func (t Time) IsZero() bool
package main import ( "time" "fmt" ) func main() { loc,_ := time.LoadLocation("UTC") now:=time.Date(1,1,1,0,0,0,0, loc) fmt.Println(now) fmt.Println(now.IsZero()) }
28.创建时区
func LoadLocation(name string) (*Location, error)
package main import ( "time" "fmt" ) func main() { loc,_ := time.LoadLocation("UTC") fmt.Println(loc) }
29.获取时区的名称
func (l *Location) String() string
package main import ( "time" "fmt" ) func main() { loc,_ := time.LoadLocation("UTC") fmt.Println(loc.String()) }
30.间隔触发器的创建和停止
func NewTicker(d Duration) *Ticker func (t *Ticker) Stop()
package main import ( "time" "fmt" ) func main() { ticker := time.NewTicker(time.Second) var i = 0 c := ticker.C for date := range c{ fmt.Println(date) i ++ if i == 5 { ticker.Stop() break } } }
31.延时异步执行
func AfterFunc(d Duration, f func()) *Timer
package main import ( "time" "fmt" ) func main() { time.AfterFunc(time.Second, func() { fmt.Println("延时1s后执行") }) time.Sleep(time.Second * 2) }
32.定时器的创建和停止
func NewTimer(d Duration) *Timer func (t *Timer) Reset(d Duration) bool func (t *Timer) Stop() bool
package main import ( "time" "fmt" ) func main() { timer := time.NewTimer(time.Second*1) c := <- timer.C fmt.Println(c) // 恢复 d,_ := time.ParseDuration("2s") timer.Reset(d) c = <- timer.C fmt.Println(c) // 停止 d,_ = time.ParseDuration("2s") timer.Reset(d) timer.Stop() c = <- timer.C fmt.Println(c) }
注意一旦我们停止了定时器,就不能继续对定时器的信道进行接受,否则程序出错
33.解析数据
func Parse(layout, value string) (Time, error) func ParseInLocation(layout, value string, loc *Location) (Time, error)
package main import ( "time" "fmt" ) func main() { const longForm = "Jan 2, 2006 at 3:04pm (MST)" t, _ := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)") fmt.Println(t) const shortForm = "2006-01-02 15:04:05.000" t, _ = time.Parse(shortForm, "2006-01-02 15:04:05.000") fmt.Println(t) }
34.将日期格式化成执行的字符串
func (t Time) Format(layout string) string
func ParseInLocation(layout, value string, loc *Location) (Time, error)
package main import ( "fmt" "time" ) func main() { fmt.Println(time.Now().Format("2018-02-02 15:04:05.000")) // 必须写下面的格式 fmt.Println(time.Now().Format("2006-01-02 15:04:05.000")) fmt.Println(time.Now().Format("2006-01-02 15:04:05")) }
package main import ( "fmt" "time" ) func main() { 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) }
36.Unix创建一个本地时间,对应sec和nsec表示的Unix时间(从January 1, 1970 UTC至该时间的秒数和纳秒数)。
package main import ( "fmt" "time" ) func main() { fmt.Println(time.Unix(10,0)) }
37.GobEncode实现了gob.GobEncoder接口
func (t *Time) GobDecode(data []byte) error
package main import ( "fmt" "time" ) func main() { // 序列化 data,_ := time.Now().GobEncode() fmt.Println(data) date := time.Now() //反序列化 date.GobDecode(data) fmt.Println(date) }
三种序列化和反序列化操作
// 序列化 func (t Time) MarshalBinary() ([]byte, error) func (t Time) MarshalJSON() ([]byte, error) func (t Time) MarshalText() ([]byte, error) // 反序列化 func (t *Time) UnmarshalBinary(data []byte) error func (t *Time) UnmarshalJSON(data []byte) error func (t *Time) UnmarshalText(data []byte) error
package main import ( "fmt" "time" ) func main() { // 序列化 data,_ := time.Now().MarshalBinary() fmt.Println(data) date := time.Now() //反序列化 date.UnmarshalBinary(data) fmt.Println(date) data,_ = time.Now().MarshalText() fmt.Printf("MarshalText:%s\n",string(data)) date = time.Now() //反序列化 date.UnmarshalText(data) fmt.Println(date) data,_ = time.Now().MarshalJSON() fmt.Printf("MarshalJSON:%s\n",string(data)) date = time.Now() //反序列化 date.UnmarshalJSON(data) fmt.Println(date) }
但将文本表示附加b到缓冲区,并返回缓冲区
func (t Time) AppendFormat(b []byte, layout string) []byte
package main import ( "fmt" "time" ) func main() { data:= time.Now().AppendFormat([]byte("当前日期为:"),"2006-01-02") fmt.Println(string(data)) }
作者:酷走天涯
链接:https://www.jianshu.com/p/895471a4af8a
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。