Skip to content

Instantly share code, notes, and snippets.

@xin053
Created September 1, 2019 11:57
Show Gist options
  • Save xin053/9b6d2505e5661af9bd6a9e31a0402f4e to your computer and use it in GitHub Desktop.
Save xin053/9b6d2505e5661af9bd6a9e31a0402f4e to your computer and use it in GitHub Desktop.
[go 标准库 time]go 标准库 time #go #标准库 #time

func After(d Duration) <-chan Time

package main

import (
	"fmt"
	"time"
)

var c chan int

func handle(int) {}

func main() {
	select {
	case m := <-c:
		handle(m)
	case <-time.After(10 * time.Second):
		fmt.Println("timed out")
	}
}

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

package main

import (
	"fmt"
	"time"
)

func main() {
	t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
	tt := time.Date(2009, time.November, 11, 7, 0, 0, 0, time.Local)
	fmt.Printf("Go launched at %s\n", t.Local())
	fmt.Printf("Go launched at %s\n", tt)
}

func (d Duration) Hours() float64

package main

import (
	"fmt"
	"time"
)

func main() {
	h, _ := time.ParseDuration("4h30m")
	fmt.Printf("I've got %.1f hours of work left.", h.Hours()) // 4.5
}

func (d Duration) String() string

package main

import (
	"fmt"
	"time"
)

func main() {
	t1 := time.Date(2016, time.August, 15, 0, 0, 0, 0, time.UTC)
	t2 := time.Date(2017, time.February, 16, 0, 0, 0, 0, time.UTC)
	fmt.Println(t2.Sub(t1).String()) // 4440h0m0s
}

func FixedZone(name string, offset int) *Location

package main

import (
	"fmt"
	"time"
)

func main() {
	loc := time.FixedZone("UTC-8", -8*60*60)
	t := time.Date(2009, time.November, 10, 23, 0, 0, 0, loc)
	fmt.Println("The time is:", t.Format(time.RFC822))
}

func ParseDuration(s string) (Duration, error)

package main

import (
	"fmt"
	"time"
)

func main() {
	hours, _ := time.ParseDuration("10h")
	complex, _ := time.ParseDuration("1h10m10s")

	fmt.Println(hours)
	fmt.Println(complex)
	fmt.Printf("there are %.0f seconds in %v\n", complex.Seconds(), complex)
}

func Sleep(d Duration)

package main

import (
	"time"
)

func main() {
	time.Sleep(100 * time.Millisecond)
}

func (t Time) Unix() int64

package main

import (
	"fmt"
	"time"
)

func main() {
	// 1 billion seconds of Unix, three ways.
	fmt.Println(time.Unix(1e9, 0).UTC())     // 1e9 seconds
	fmt.Println(time.Unix(0, 1e18).UTC())    // 1e18 nanoseconds
	fmt.Println(time.Unix(2e9, -1e18).UTC()) // 2e9 seconds - 1e18 nanoseconds

	t := time.Date(2001, time.September, 9, 1, 46, 40, 0, time.UTC)
	fmt.Println(t.Unix())     // seconds since 1970
	fmt.Println(t.UnixNano()) // nanoseconds since 1970

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment