23 September 2017

Table of Contents

Constants

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"
)
now := time.Now()

formate := "Mon 2006-01-02 15:04:05"

local1, _ := time.LoadLocation("Local")
local2, _ := time.LoadLocation("Asia/Shanghai")

fmt.Println(now.In(local1).Format(formate))
fmt.Println(now.In(local2).Format(formate))

func After(d Duration) <-chan Time

After waits for the duration to elapse and then sends the current time on the returned channel.

It is equivalent to NewTimer(d).C. The underlying Timer is not recovered by the garbage collector until the timer fires. If efficiency is a concern, use NewTimer instead and call Timer.Stop if the timer is no longer needed.

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

func Sleep(d Duration)

time.Sleep(100 * time.Millisecond)

func Tick(d Duration) <-chan Time

Tick is a convenience wrapper for NewTicker providing access to the ticking channel only.

While Tick is useful for clients that have no need to shut down the Ticker, be aware that without a way to shut it down the underlying Ticker cannot be recovered by the garbage collector; it "leaks". Unlike NewTicker, Tick will return nil if d <= 0.

c := time.Tick(1 * time.Minute)
for now := range c {
      fmt.Printf("%v %s\n", now, statusUpdate())
}

type Duration

type Duration int64
second := time.Second
fmt.Print(int64(second/time.Millisecond)) // prints 1000


seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
const (
      Nanosecond  Duration = 1
      Microsecond          = 1000 * Nanosecond
      Millisecond          = 1000 * Microsecond
      Second               = 1000 * Millisecond
      Minute               = 60 * Second
      Hour                 = 60 * Minute
)
D1, _ := time.ParseDuration("2h1xm10s")
D2, _ := time.ParseDuration("6h")
fmt.Printf("%v\n", D1.Seconds()) // 7270
fmt.Printf("%v\n", D2.Seconds()) // 21600

func ParseDuration(s string) (Duration, error)

ParseDuration parses a duration string. A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".

func Since(t Time) Duration

Since returns the time elapsed since t. It is shorthand for time.Now().Sub(t).

func Until(t Time) Duration

Until returns the duration until t. It is shorthand for t.Sub(time.Now()).

func (d Duration) Hours() float64

func (d Duration) Minutes() float64

func (d Duration) Nanoseconds() int64

func (d Duration) Round(m Duration) Duration

Round returns the result of rounding d to the nearest multiple of m.

The rounding behavior for halfway values is to round away from zero. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, Round returns the maximum (or minimum) duration. If m <= 0, Round returns d unchanged.

func (d Duration) Seconds() float64

func (d Duration) String() string

func (d Duration) Truncate(m Duration) Duration

type Location

var utcLoc = Location{name: "UTC"}  // 设置一个 utc Location

var UTC *Location = &utcLoc         // 将 UTC 执行 utc location

var localLoc Location               // 定义一个 localLoc

var Local *Location = &localLoc     // 定义一个 Local

func (l *Location) get() *Location {
      if l == nil {
              return &utcLoc
      }
      if l == &localLoc {
              localOnce.Do(initLocal)
      }
      return l
}

func FixedZone(name string, offset int) *Location

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

formate := "2006-01-02 15:04:05 Mon"

local, _ := time.LoadLocation("Asia/Shanghai")

fmt.Println(now.In(local).Format(formate))

func (l *Location) String() string

type Month

const (
      January Month = 1 + iota
      February
      March
      April
      May
      June
      July
      August
      September
      October
      November
      December
)

func (m Month) String() string

type ParseError

func (e *ParseError) Error() string

type Ticker

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

time.Sleep(time.Second * 5)
ticker.Stop()
fmt.Println("Ticker stopped")

func NewTicker(d Duration) *Ticker

func (t *Ticker) Stop()

type Time

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time

t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
fmt.Printf("Go launched at %s\n", t.Local())

func Now() Time

func Parse(layout, value string) (Time, error)

t, _ := time.Parse(time.RFC3339, "2012-11-01T22:08:41+00:00")

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

func main() {
     c := make(chan int)
     isReturn := make(chan bool)
     go func() {
             for {
                     select {
                     case v := <-c:
                             println(v)
                     case <-time.After(5 * time.Second):
                             println("timeout")
                             isReturn <- true
                             break
                     }
             }
     }()

     <-isReturn
}

func (t Time) AppendFormat(b []byte, layout string) []byte

func (t Time) Before(u Time) bool

func (t Time) Clock() (hour, min, sec int)

func (t Time) Date() (year int, month Month, day int)

year, month, day := time.Now().Date()
if year == 2016 && month == time.November && day == 10 {
     fmt.Println("Happy Go day!")
}

func (t Time) Day() int

func (t Time) Equal(u Time) bool

func (t Time) Format(layout string) string

func (t *Time) GobDecode(data []byte) error

func (t Time) GobEncode() ([]byte, error)

func (t Time) Hour() int

func (t Time) ISOWeek() (year, week int)

func (t Time) In(loc *Location) Time

func (t Time) IsZero() bool

func (t Time) Local() Time

func (t Time) Location() *Location

func (t Time) MarshalBinary() ([]byte, error)

func (t Time) MarshalJSON() ([]byte, error)

func (t Time) MarshalText() ([]byte, error)

func (t Time) Minute() int

func (t Time) Month() Month

func (t Time) Nanosecond() int

func (t Time) Round(d Duration) Time

func (t Time) Second() int

func (t Time) String() string

func (t Time) Sub(u Time) Duration

func (t Time) Truncate(d Duration) Time

func (t Time) UTC() Time

func (t Time) Unix() int64

func (t Time) UnixNano() int64

fmt.Printf("%v\n", time.Now().Unix())     // 1505051013
fmt.Printf("%v\n", time.Now().UnixNano()) // 1505051013176066347

func (t *Time) UnmarshalBinary(data []byte) error

func (t *Time) UnmarshalJSON(data []byte) error

func (t *Time) UnmarshalText(data []byte) error

func (t Time) Weekday() Weekday

func (t Time) Year() int

func (t Time) YearDay() int

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

type Timer

timer1 := time.NewTimer(time.Second * 2)   // 设置一个定时器

<-timer1.C // 等待定时器返回
fmt.Printf("after 2 second call: timer 1 expired\n")

timer2 := time.NewTimer(time.Second * 3)   // 设置一个定时器
go func() {
      <-timer2.C
      fmt.Printf("timer 2 expired\n")
}()

// 如果没有 Sleep,那么 timer2 不会被执行,因为程序在 main 线程,已经退出了
time.Sleep(time.Second * 10)
timer1 := time.NewTimer(time.Second * 2)   // 设置一个定时器

<-timer1.C // 等待定时器返回
fmt.Printf("after 2 second call: timer 1 expired\n")

timer2 := time.NewTimer(time.Second * 3)   // 设置一个定时器
go func() {
      <-timer2.C
      fmt.Printf("timer 2 expired\n")
}()


if timer2.Stop() {  // 停止这个定时器,timer2 不会再被执行
      fmt.Printf("timer 2 stopped\n")
}

time.Sleep(time.Second * 10)

func AfterFunc(d Duration, f * func()) *Timer

d := time.Duration(time.Second * 2)
timer := time.AfterFunc(d, func() {
     fmt.Printf("you call me\n")
})

// 如果不注释掉下面这行就会造成 deadlock,即 AfterFunc 的 func 函数里面实际上也运行了 <-timer.C
// <-timer.C
time.Sleep(time.Second * 3)

func NewTimer(d Duration) *Timer

func (t *Timer) Reset(d Duration) bool

func (t *Timer) Stop() bool

type Weekday

type Weekday int

const (
      Sunday Weekday = iota
      Monday
      Tuesday
      Wednesday
      Thursday
      Friday
      Saturday
)

func (d Weekday) String() string