go 时间和日期函数

2019-03-02  本文已影响0人  StevenQin

1、时间和日期相关函数,需要引入 time包。
2、time.Time类型,用来表示时间。

    //获取当前时间
    now := time.Now()
    fmt.Printf("now=%v,now的类型是%T\n", now, now)

3、获取当前时间方法 now := time.Now()
4、获取其它日期信息

//获取当前时间
    now := time.Now()
    fmt.Printf("now=%v,now的类型是%T\n", now, now)
    
    //now返回的是个结构体struct,里面有很多方法,类似于对象
    //通过now可以获得年月日,时分秒
    fmt.Printf("年=%v\n", now.Year())
    fmt.Printf("月=%v\n", now.Month())
    fmt.Printf("月=%v\n", int(now.Month()))
    fmt.Printf("日=%v\n", now.Day())
    fmt.Printf("时=%v\n", now.Hour())
    fmt.Printf("分=%v\n", now.Minute())
    fmt.Printf("秒=%v\n", now.Second())

5、格式化日期和时间

    //获取当前时间
    now := time.Now()
    fmt.Printf("now=%v,now的类型是%T\n", now, now)
    //格式化时间
    fmt.Printf("当前日期是:%02d-%02d-%02d %02d:%02d:%02d \n", now.Year(),
        now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
    //Sprintf 转成字符串的形式
    dateStr := fmt.Sprintf("当前日期是:%02d-%02d-%02d %02d:%02d:%02d \n", now.Year(),
        now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
    fmt.Printf("dateStr=%v\n", dateStr)
    //获取当前时间
    now := time.Now()
    fmt.Printf("now=%v,now的类型是%T\n", now, now)
    //格式化时间
    fmt.Printf(now.Format("2006-01-02 15:04:05"))
    fmt.Println()
    fmt.Printf(now.Format("2006-01-02"))
    fmt.Println()
    fmt.Printf(now.Format("15:04:05"))
    fmt.Println()
    fmt.Printf(now.Format("15:04"))
    fmt.Println()

6、时间的常量

//常量定义 //见文档
const (
    Nanosecond  Duration = 1
    Microsecond          = 1000 * Nanosecond
    Millisecond          = 1000 * Microsecond
    Second               = 1000 * Millisecond
    Minute               = 60 * Second
    Hour                 = 60 * Minute
)

常量的作用是:用来获取指定时间单位的时间,比如:100毫秒写法是 100* time.Millisecond

7、休眠 (结合sleep来使用时间常量)

需求:每隔0.1秒,打印一个数字,到100时退出

package main

import (
    "fmt"
    _ "strconv"
    _ "strings"
    "time"
)

func main() {
    //需求:每隔0.1秒,打印一个数字,到100时退出
    i := 0
    for {
        i++
        fmt.Println(i)
        time.Sleep(time.Millisecond * 100)
        if i == 100 {
            break
        }
    }
}

8、获取当前Unix时间戳和Unixnano时间戳(作用是:获取随机的数字)

    now := time.Now()
    fmt.Printf("unix时间戳是:%v, unixnano时间戳是:%v \n", now.Unix(), now.UnixNano())

计算test03函数执行的时间

package main

import (
    "fmt"
    "strconv"
    _ "strings"
    "time"
)

func test03() {
    str := ""
    for i := 0; i < 100000; i++ {
        str += "hello" + strconv.Itoa(i) //当i转为字符串
    }
}
func main() {
    //执行前先获取unix时间戳
    start := time.Now().Unix()
    test03()
    end := time.Now().Unix()
    fmt.Printf("用时为%v秒。\n", end-start)
}
上一篇 下一篇

猜你喜欢

热点阅读