本章就來學(xué)習(xí)時(shí)間相關(guān)的所有操作
1.延遲d秒后返回通過信道返回時(shí)間值
func After(d Duration) <-chan Time
示例
package main
import (
"time"
"fmt"
)
func main() {
date := <- time.After(3*time.Second)
fmt.Println(date)
}
3 秒后會返回一個(gè)chan time 數(shù)據(jù),程序繼續(xù)向下執(zhí)行
2.當(dāng)前的 goroutine 睡眠至少持續(xù)時(shí)間d 如果d為0或者負(fù)值程序立即執(zhí)行
func Sleep(d Duration)
package main
import (
"time"
"fmt"
)
func main() {
time.Sleep(1*time.Second)
fmt.Println("延時(shí)1s執(zhí)行")
}
3. 不能被關(guān)閉的間隔觸發(fā)器
func Tick(d Duration) <-chan Time
這個(gè)方法可以間隔的像信道填值,但是沒有辦法阻止這個(gè)過程
示例
package main
import (
"time"
"fmt"
)
func main() {
c := time.Tick(1 * time.Second)
for now := range c {
fmt.Printf("延時(shí)執(zhí)行該做的事情 %s\n", now)
}
}
4.計(jì)算持續(xù)時(shí)間
type Duration int64
持續(xù)時(shí)間表示兩個(gè)瞬間之間的經(jīng)過時(shí)間徊都,為int64納秒計(jì)數(shù)柬甥。
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.將字符串解析成功時(shí)間格式
func ParseDuration(s string) (Duration, error)
有效時(shí)間單位為“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.計(jì)算從t到time.now 的時(shí)間
func Since(t Time) Duration
package main
import (
"time"
"fmt"
)
func main() {
// 將時(shí)間先轉(zhuǎn)換成時(shí)間戳
s := time.Now().Local().UnixNano()
// 已系統(tǒng)起始日期為基準(zhǔn)計(jì)算偏移后的time
t := time.Unix(0, s-1000000)
// 與當(dāng)前日期進(jìn)行運(yùn)算計(jì)算時(shí)間差
elapsed := time.Since(t)
fmt.Println(elapsed)
}
7.Until 從t計(jì)算到now的時(shí)間差
func Until(t Time) Duration
package main
import (
"time"
"fmt"
)
func main() {
// 將時(shí)間先轉(zhuǎn)換成時(shí)間戳
s := time.Now().Local().UnixNano()
// 已系統(tǒng)起始日期為基準(zhǔn)計(jì)算偏移后的time
t := time.Unix(0, s-1000000)
// 與當(dāng)前日期進(jìn)行運(yùn)算計(jì)算時(shí)間差
elapsed := time.Until(t)
fmt.Println(elapsed)
}
8.獲取日期的年月日時(shí)分秒
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 // 當(dāng)月多少號
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() {
// 將時(shí)間先轉(zhuǎn)換成時(shí)間戳
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.計(jì)算總計(jì)多少小時(shí)跪腹,分鐘 等
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() {
// 將時(shí)間先轉(zhuǎn)換成時(shí)間戳
now:= time.Now()
t := now.Add(time.Second*3600)
d := time.Until(t)
fmt.Printf("共小時(shí):%f\n",d.Hours())
fmt.Printf("共分鐘:%f\n",d.Minutes())
fmt.Printf("共秒:%f\n",d.Seconds())
fmt.Printf("共納秒:%d\n",d.Nanoseconds())
}
10. 將四舍五入d的結(jié)果值
func (d Duration) Round(m Duration) Duration
該時(shí)間點(diǎn)應(yīng)該滿足從Time零值到該時(shí)間點(diǎn)的時(shí)間段能整除d;如果有兩個(gè)滿足要求的時(shí)間點(diǎn)开伏,距離t相同膀跌,會向上舍入;如果d <= 0固灵,會返回t的拷貝
通俗的將,就是講時(shí)間保留到指定的時(shí)間單位上如 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的時(shí)間點(diǎn)
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.返回格式化時(shí)間的字符串
func (d Duration) String() string
package main
import (
"time"
"fmt"
)
func main() {
t:=time.Now()
fmt.Println(t.String())
}
13.獲取當(dāng)前日期
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.在當(dāng)前日期上增加年月日的偏移量
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.獲取時(shí)分秒
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.計(jì)算當(dāng)前時(shí)間到指定時(shí)間的時(shí)間差
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())
}
獲取時(shí)間戳
func (t Time) Unix() int64
func (t Time) UnixNano() int64
示例
package main
import (
"time"
"fmt"
)
func main() {
today := time.Now()
// 返回時(shí)間戳 單位s
fmt.Println(today.Unix())
// 返回時(shí)間戳 單位納秒
fmt.Println(today.UnixNano())
}
20.判斷兩個(gè)日期是否相等
func (t Time) Equal(u Time) bool
package main
import (
"time"
"fmt"
)
func main() {
today := time.Now()
fmt.Println(today.Equal(today))
}
21.獲取零時(shí)區(qū)的日期
func (t Time) UTC() Time
package main
import (
"time"
"fmt"
)
func main() {
today := time.Now()
fmt.Println(today)
fmt.Println(today.UTC())
}
22.計(jì)算當(dāng)前時(shí)區(qū)和零時(shí)區(qū)之間的偏移量
func (t Time) Zone() (name string, offset int)
Zone計(jì)算t所在的時(shí)區(qū)捅伤,返回該時(shí)區(qū)的規(guī)范名(如"CET")和該時(shí)區(qū)相對于UTC的時(shí)間偏移量(單位秒)
package main
import (
"time"
"fmt"
)
func main() {
today := time.Now()
name,offset := today.Zone()
fmt.Println(name)
fmt.Println(offset/3600)
}
時(shí)差八個(gè)小時(shí)
23. 返回采用本地和本地時(shí)區(qū)
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.獲取指定時(shí)區(qū)的日期
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.通過年月日時(shí)分秒時(shí)區(qū)創(chuàng)建日期
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.獲取當(dāng)前日期是當(dāng)年的多少第幾周
![image.png](http://upload-images.jianshu.io/upload_images/1594482-ed4acdaa971be2cc?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
返回時(shí)間點(diǎn)t對應(yīng)的ISO 9601標(biāo)準(zhǔn)下的年份和星期編號。星期編號范圍[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.創(chuàng)建時(shí)區(qū)
func LoadLocation(name string) (*Location, error)
package main
import (
"time"
"fmt"
)
func main() {
loc,_ := time.LoadLocation("UTC")
fmt.Println(loc)
}
29.獲取時(shí)區(qū)的名稱
func (l *Location) String() string
package main
import (
"time"
"fmt"
)
func main() {
loc,_ := time.LoadLocation("UTC")
fmt.Println(loc.String())
}
30.間隔觸發(fā)器的創(chuàng)建和停止
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.延時(shí)異步執(zhí)行
func AfterFunc(d Duration, f func()) *Timer
package main
import (
"time"
"fmt"
)
func main() {
time.AfterFunc(time.Second, func() {
fmt.Println("延時(shí)1s后執(zhí)行")
})
time.Sleep(time.Second * 2)
}
32.定時(shí)器的創(chuàng)建和停止
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)
// 恢復(fù)
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)
}
注意一旦我們停止了定時(shí)器,就不能繼續(xù)對定時(shí)器的信道進(jìn)行接受仍秤,否則程序出錯(cuò)
33.解析數(shù)據(jù)
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.將日期格式化成執(zhí)行的字符串
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創(chuàng)建一個(gè)本地時(shí)間熄诡,對應(yīng)sec和nsec表示的Unix時(shí)間(從January 1, 1970 UTC至該時(shí)間的秒數(shù)和納秒數(shù))。
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println(time.Unix(10,0))
}
37.GobEncode實(shí)現(xiàn)了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到緩沖區(qū),并返回緩沖區(qū)
func (t Time) AppendFormat(b []byte, layout string) []byte
package main
import (
"fmt"
"time"
)
func main() {
data:= time.Now().AppendFormat([]byte("當(dāng)前日期為:"),"2006-01-02")
fmt.Println(string(data))
}