23.Go语言时间编程

Go语言时间编程

时间元素编程

打印计算机中的当前时间

package main

import (
    "fmt"
    "time"
)

func main(){
    fmt.Println(time.Now())
}

//2021-02-01 22:23:16.2223868 +0800 CST m=+0.002992601

让程序休眠

程序休眠意味着暂定程序的执行,在休眠期间,程序什么都不做

time.Sleep(3 * time.Second)

设置超时时间

package main

import(
    "fmt"
    "time"
)

func main(){
    for {
        select {
        //在2秒后执行内容
        case <- time.After(2 * time.Second):
            fmt.Println("result")
        }
    }
}
// result
// result
// result
// result
// result
// ...

使用ticker

ticker可让代码每隔特定的时间就重复执行一次

package main

import (
    "fmt"
    "time"
)

func main(){
    c := time.Tick(2 * time.Second)
    i := 0

    for  range c{
        fmt.Println("hello")
        i += 1
        if i >= 5{
            return 
        }
    }
}
// hello
// hello
// hello
// hello
// hello

以字符串格式显示时间

以下是不同时间标准及其字符串表示

image-20210201234213894

package main

import (
    "fmt"
    "log"
    "time"
)

func main(){
    s := "2006-01-02T15:04:05+07:00"
    t,err:= time.Parse(time.RFC3339,s)
    if err != nil{
        log.Fatal(err)
    }
    fmt.Println(t)
}
// 2006-01-02 15:04:05 +0700 +0700
  • 将时间字符串解析为time结构体

使用time结构体

//获取小时
t.Hour()

//获取分钟
t.Minute()

//获取秒
t.Second()

//获取日期
t.Day()

//获取月份
t.Month()

//获取UNIX时间
t.Unix()

//获取星期
t.Wenkday()

时间加减

//加时间
nt := t.Add(2 * time.Scond)

//减时间
nt := t.Sub(2 * time.Scond)

比较两个不同的结构体

//today是否在tomorrow之后
today.after(tomorrow)

//today是否在tomorrow之前
today.before(tomorrow)

//today是否与tomorrow相等
today.equal(tomorrow)
© 版权声明
THE END
喜欢就支持以下吧
点赞0 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容