1、获取当前时间的方法

now := time.Now() // now的类型就是time.Time

  

2、获取到其他的日期信息

func main() {
    now := time.Now() // now的类型就是time.Time

    fmt.Println("当前年:", now.Year())
    fmt.Println("当前月:", now.Month())
    fmt.Println("当前月:", int(now.Month()))
    fmt.Println("当前年:", now.Day())
    fmt.Println("当前时:", now.Hour())
    fmt.Println("当前分:", now.Minute())
    fmt.Println("当前秒:", now.Minute())
}

  

3、格式化日期和时间 Format("2006/01/02 15:04:05")

now := time.Now() // now的类型就是time.Time

fmt.Println("当前时间:", now.Format("2006/01/02 15:04:05"))
fmt.Println("当前年月日:", now.Format("2006-01-02"))
fmt.Println("时分秒:", now.Format("15:04:05"))

 

4、时间的常量  

type Duration int64
const (
    Nanosecond  Duration = 1 // 纳秒
    Microsecond          = 1000 * Nanosecond // 微秒
    Millisecond          = 1000 * Microsecond // 毫秒
    Second               = 1000 * Millisecond // 秒
    Minute               = 60 * Second // 分钟
    Hour                 = 60 * Minute // 小时
)

  

5、休眠

time.Sleep(d Duration)

举例:

now1 := time.Now()
fmt.Println("休眠前时间:", now1.Format("2006/01/02 15:04:05"))
time.Sleep(2 * time.Second) // 休眠2秒
now2 := time.Now()
fmt.Println("休眠后时间:", now2.Format("2006/01/02 15:04:05"))

  

6、获取当前的unix时间戳和unixnano时间戳(作用是可以获取随机数字)

func (t Time) Unix() int64
func (t Time) UnixNano() int64

举例:

now := time.Now()
fmt.Println("Unix时间戳:", now.Unix(), "UnixNano时间戳:", now.UnixNano())

  

posted on 2022-03-03 00:14  smile学子  阅读(19)  评论(0编辑  收藏  举报