golang中time包用法

time包中包括兩類時間:時間點(某一時刻)和時常(某一段時間)json

1時間常量(時間格式化)
數組

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"
)
這些常量是在time包中進行time 格式化 和time解析而預約義的一些常量,其實他們使用的都是一個特定的時間:
Mon Jan 2 15:04:05 MST 2006
這個時間是Unix time 1136239445,由於MST是GMT-0700,因此這個指定的時間也能夠看作

01/02 03:04:05PM '06 -0700
可見程序猿也有調皮的一面.

所以咱們只須要利用上面這些時間變能夠隨意的指定本身的時間格式,例如:函數

layout := "01__02-2006 3.04.05 PM"編碼

fmt.Println(time.Now().Format(layout))spa

便會輸出相似的時間:11__26-2014 8.40.00 PMcode


2 函數orm

time 組成:協程

   time.Duration(時間長度,消耗時間)事件

   time.Time(時間點)字符串

   time.C(放時間的channel通道)(注:Time.C:=make(chan time.Time))


After函數:

1)func After(d Duration) <-chan Time

表示多少時間以後,可是在取出channel內容以前不阻塞,後續程序能夠繼續執行

2)func Sleep(d Duration)
表示休眠多少時間,休眠時處於阻塞狀態,後續程序沒法執行.
舉例說明兩者區別:

fmt.Println("hello")

chan := time.After(time.Secone*1)

fmt.Println("World")

則程序在執行完輸出hello後,接着便輸出world,不用等待1s,可是1s後,chan中有數據,此時chan阻塞

mt.Println("hello")

chan := time.Sleep(time.Secone*1)

fmt.Println("World")

則表示在輸出hello後,程序變休眠1s中,而後才輸出World.因而可知阻塞和非阻塞即是這兩個函數的本質區別.

鑑於After特性,其一般用來處理程序超時問題,以下所示:

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

3)func Tick(d Duration) <-chan Time
time.Tick(time.Duration)用法和time.After差很少, 可是它是表示每隔多少時間以後,是一個重複的過程,其餘與After一致


4)type Duration int64 //時間長度,其對應的時間單位有Nanosecond,Microsecond,Millisecond,Second,Minute,Hour

    (1)func ParseDuration(s string) (Duration, error)//傳入字符串,返回響應的時間,其中傳入的字符串中的有效時間單位以下:h,m,s,ms,us,ns,其餘單位均無效,若是傳入無效時間單位,則會返回0

    (2)func Since(t Time) Duration //表示自從t時刻之後過了多長時間,是一個時間段,至關於time.Now().Sub(t)

 (3)func (d Duration) Hours() float64 //將制定時間段換算爲float64類型的Hour爲單位進行輸出


 (4)func (d Duration) Minutes() float64 //將制定時間段換算爲float64類型的Minutes爲單位進行輸出


 (5)func (d Duration) Nanoseconds() int64 //將制定時間段換算爲int64類型的Nanoseconds爲單位進行輸出


 (6)func (d Duration) Seconds() float64 //將制定時間段換算爲float64類型的Seconds爲單位進行輸出

    (7)func(d Duration) String() string  //與ParseDuration函數相反,該函數是將時間段轉化爲字符串輸出


5) type Location
func FixedZone(name string, offset int) *Location
func LoadLocation(name string) (*Location, error)
func (l *Location) String() string


6)type Month //定義了1年的12個月


func (m Month) String() string  //將時間月份以字符串形式打印出來.如fmt.Println(time.June.String())則打印出June


7)type ParseError
func (e *ParseError) Error() string
8)type Ticker  //主要用來按照指定的時間週期來調用函數或者計算表達式,一般的使用方式是利用go新開一個協程使用,它是一個斷續器
func NewTicker(d Duration) *Ticker    //新生成一個ticker,此Ticker包含一個channel,此channel以給定的duration發送時間。duration d必須大於0
func (t *Ticker) Stop()  //用於關閉相應的Ticker,但並不關閉channel

例子以下:

使用時間控制中止ticker

	ticker := time.NewTicker(time.Millisecond * 500)
    go func() {
        for t := range ticker.C {
            fmt.Println("Tick at", t)
        }
    }()

time.Sleep(time.Millisecond * 1500)   //阻塞,則執行次數爲sleep的休眠時間/ticker的時間
    ticker.Stop()     
    fmt.Println("Ticker stopped")

使用channel控制中止ticker

ticker := time.NewTicker(time.Millisecond * 500)
c := make(chan int,num) //num爲指定的執行次數
go func() {
	for t := range ticker.C {
              c<-1
               fmt.Println("Tick at", t)
				
	}
}()
		
ticker.Stop()
這種狀況下,在執行num次以Ticker時間爲單位的函數以後,c channel中已滿,之後便不會再執行對應的函數.

9)type Time //包括日期和時間
func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time //按照指定格式輸入數據後,便會按照以下格式輸出對應的時間,輸出格式爲
yyyy-mm-dd hh:mm:ss + nsec nanoseconds, 其中loc必須指定,不然便會panic,
例子以下:
t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
fmt.Printf("Go launched at %s\n", t.Local())
輸出爲:
Go launched at 2009-11-10 15:00:00 -0800 PST

func Now() Time //返回當前時間,包括日期,時間和時區


func Parse(layout, value string) (Time, error) //輸入格式化layout和時間字符串,輸出時間


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  //判斷時間t是否在時間u的後面


func (t Time) Before(u Time) bool //判斷時間t是否在時間u的前面


func (t Time) Clock() (hour, min, sec int) //獲取時間t的hour,min和second


func (t Time) Date() (year int, month Month, day int) //獲取時間t的year,month和day


func (t Time) Day() int   //獲取時間t的day


func (t Time) Equal(u Time) bool  //判斷時間t和時間u是否相同


func (t Time) Format(layout string) string  //時間字符串格式化


func (t *Time) GobDecode(data []byte) error //編碼爲god


func (t Time) GobEncode() ([]byte, error)//解碼god


func (t Time) Hour() int //獲取時間t的小時


func (t Time) ISOWeek() (year, week int)//獲取時間t的年份和星期


func (t Time) In(loc *Location) Time//獲取loc時區的時間t的對應時間


func (t Time) IsZero() bool //判斷是否爲0時間實例January 1, year 1, 00:00:00 UTC


func (t Time) Local() Time //獲取當地時間


func (t Time) Location() *Location   //獲取當地時區


func (t Time) MarshalBinary() ([]byte, error) //marshal binary序列化,將時間t序列化後存入[]byte數組中


func (t Time) MarshalJSON() ([]byte, error)     //marshal json序列化,將時間t序列化後存入[]byte數組中


func (t Time) MarshalText() ([]byte, error)    //marshal text序列化,將時間t序列化後存入[]byte數組中

舉例說明:
a := time.Now()
    fmt.Println(a)   輸出:2014-11-27 14:58:31.583853811 +0800 CST
    b, _ := a.MarshalText()
    fmt.Println(b)   輸出:[50 48 49 52 45 49 49 45 50 55 84 49 52 58 53 56 58 51 49 46 53 56 51 56 53 51 56 49 49 43 48 56 58 48 48]
    var c = new(time.Time)
    fmt.Println(c)   輸出:0001-01-01 00:00:00 +0000 UTC
    c.UnmarshalText(b)
    fmt.Println(c)   輸出:2014-11-27 14:58:31.583853811 +0800 CST
可見Marshal類的函數只是提供一個將時間t序列化爲[]byte數組的功能,利用UnMarshal類的函數能夠獲取到原來的時間t

func (t Time) Minute() int  //獲取時間t的分鐘


func (t Time) Month() Month //獲取時間t的月份


func (t Time) Nanosecond() int //獲取時間t的納秒


func (t Time) Round(d Duration) Time //將時間t以d Duration爲單位進行四捨五入求近似值.

示例以下:

代碼:

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

輸出:

t.Round(   1ns) = 12:15:30.918273645
t.Round(   1µs) = 12:15:30.918274
t.Round(   1ms) = 12:15:30.918
t.Round(    1s) = 12:15:31
t.Round(    2s) = 12:15:30
t.Round(  1m0s) = 12:16:00
t.Round( 10m0s) = 12:20:00
t.Round(1h0m0s) = 12:00:00

func (t Time) Second() int //獲取時間t的秒


func (t Time) String() string //獲取時間t的字符串表示


func (t Time) Sub(u Time) Duration //與Add相反,Sub表示從時間t中減去時間u


func (t Time) Truncate(d Duration) Time //去尾法求近似值

示例代碼以下:

代碼:

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

輸出:

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


func (t Time) UTC() Time //將本地時間變換爲UTC時區的時間並返回


func (t Time) Unix() int64 //返回Unix時間,該時間是從January 1, 1970 UTC這個時間開始算起的.


func (t Time) UnixNano() int64 //以納秒爲單位返回Unix時間


func (t *Time) UnmarshalBinary(data []byte) error //將data數據反序列化到時間t中


func (t *Time) UnmarshalJSON(data []byte) (err error) //將data數據反序列化到時間t中


func (t *Time) UnmarshalText(data []byte) (err error) //將data數據反序列化到時間t中


func (t Time) Weekday() Weekday //獲取時間t的Weekday


func (t Time) Year() int   //獲取時間t的Year


func (t Time) YearDay() int     //獲取時間t的YearDay,即1年中的第幾天


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


10)type Timer //用於在指定的Duration類型時間後調用函數或計算表達式,它是一個計時器


func AfterFunc(d Duration, f func()) *Timer //和After差很少,意思是多少時間以後執行函數f


func NewTimer(d Duration) *Timer //使用NewTimer(),能夠返回的Timer類型在計時器到期以前,取消該計時器


func (t *Timer) Reset(d Duration) bool //從新設定timer t的Duration d.


func (t *Timer) Stop() bool //阻止timer事件發生,當該函數執行後,timer計時器中止,相應的事件再也不執行

11)type Weekday func (d Weekday) String() string //獲取一週的字符串

相關文章
相關標籤/搜索