要使用Go语言打印计算机中的当前时间,可使用函数Now。
import(
"time"
)
time.Now()
time.Sleep(3 * time.Second)
要在特定的时间过后执行某项操作,可使用函数After。
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("You have 2 seconds to calculate 19*4")
for {
select {
case <-time.After(2 * time.Second):
fmt.Println("Time's up")
return
}
}
}
使用ticker可让代码每隔特定的时间就重复执行一次。需要在很长的时间内定期执行任务时,这么做很有用。
package main
import (
"fmt"
"time"
)
func main() {
c := time.Tick(2 * time.Second)
for t := range c {
fmt.Printf("The time is now %v\n", t)
}
}
package main
import (
"fmt"
"log"
"time"
)
func main() {
s := "2020-07-07T12:00:00+08:00"
t, err := time.Parse(time.RFC3339, s)
if err != nil {
log.Fatal(err)
}
fmt.Printf("The hour is %v\n", t.Hour())
fmt.Printf("The minute is %v\n", t.Minute())
fmt.Printf("The second is %v\n", t.Second())
fmt.Printf("The Unix time is %v\n", t.Unix())
fmt.Printf("The day is %v\n", t.Day())
}
The hour is 12
The minute is 0
The second is 0
The Unix time is 1594152000
The day is 7
对于"2020-07-07T12:00:00+08:00"的说明:
我们经常需要确定一个事件发生在另一个事件之前、之后还是它们是同时发生的。为让您能够这样做,time包提供了方法Before、After和Equal。这些方法都比较两个Time结构体,并返回一个布尔值。
package main
import (
"fmt"
"log"
"time"
)
func main() {
s1 := "2020-07-07T12:00:00+08:00"
today, err := time.Parse(time.RFC3339, s1)
if err != nil {
log.Fatal(err)
}
s2 := "2020-07-08T12:00:00+08:00"
tomorrow, err := time.Parse(time.RFC3339, s2)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%v\n", today.After(tomorrow))
fmt.Printf("%v\n", today.Before(tomorrow))
fmt.Printf("%v\n", today.Equal(tomorrow))
}