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 数据,程序继续向下执行


image.png

2.当前的 goroutine 睡眠至少持续时间d 如果d为0或者负值程序立即执行

func Sleep(d Duration)

package main

import (
  "time"
  "fmt"
)
func main() {
  time.Sleep(1*time.Second)
  fmt.Println("延时1s执行")
}
image.png

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)
  }
}
time 用法大全_第1张图片
image.png

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)
}
image.png

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)
}
time 用法大全_第2张图片
image.png

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)
}
image.png

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)
}
image.png

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)
  }
image.png

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())
  }
time 用法大全_第3张图片
image.png

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

  }
time 用法大全_第4张图片
image.png

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"))
  }
  }
time 用法大全_第5张图片
image.png

12.返回格式化时间的字符串

func (d Duration) String() string

package main
import (
  "time"
  "fmt"
)
func main() {
  t:=time.Now()
  fmt.Println(t.String())
  }
image.png

13.获取当前日期

func Now() Time

package main

import (
  "time"
  "fmt"
)
func main() {
   fmt.Println(time.Now())
 }
image.png

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)
 }
image.png

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))
 }
image.png

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

image.png

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

image.png

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

image.png

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())
 }
image.png

获取时间戳

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())
 }
image.png

20.判断两个日期是否相等

func (t Time) Equal(u Time) bool

package main

import (
  "time"
  "fmt"
)

func main() {
  today := time.Now()
 fmt.Println(today.Equal(today))
 }
image.png

21.获取零时区的日期

func (t Time) UTC() Time

package main

import (
  "time"
  "fmt"
)

func main() {
  today := time.Now()
 fmt.Println(today)
  fmt.Println(today.UTC())
 }
image.png

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)
 }
image.png

时差八个小时

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)
 }
image.png

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)
 }
image.png

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

image.png

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)
 }
image.png

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())
 }
image.png

28.创建时区

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

package main

import (
  "time"
  "fmt"
)

func main() {
  loc,_ := time.LoadLocation("UTC")
  fmt.Println(loc)
 }
image.png

29.获取时区的名称

func (l *Location) String() string

package main

import (
  "time"
  "fmt"
)

func main() {
  loc,_ := time.LoadLocation("UTC")
  fmt.Println(loc.String())
 }
image.png

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
    }

  }
}

time 用法大全_第6张图片
image.png

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)

}
image.png

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)
}
time 用法大全_第7张图片
image.png

注意一旦我们停止了定时器,就不能继续对定时器的信道进行接受,否则程序出错

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

image.png

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"))
}
time 用法大全_第8张图片
image.png
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)
}

image.png

36.Unix创建一个本地时间,对应sec和nsec表示的Unix时间(从January 1, 1970 UTC至该时间的秒数和纳秒数)。

package main

import (
  "fmt"
  "time"
)
func main() {
fmt.Println(time.Unix(10,0))
}
image.png

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)
}
time 用法大全_第9张图片
image.png

三种序列化和反序列化操作

// 序列化
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)

}
time 用法大全_第10张图片
image.png

但将文本表示附加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))
}

time 用法大全_第11张图片
image.png

你可能感兴趣的:(time 用法大全)