zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【一Go到底】第二十四天---时间和日期函数

Go日期 函数 时间 到底 ---
2023-06-13 09:14:30 时间

一、简介

  1. 因为日期和时间相关的函数存在于time包中,所以需要导入time包
  2. time.Time 类型 ,表示时间 —> 详见案例解析
  3. 获取到当前时间的方法 —> now := time.Now() // now类型为 time.Time
  4. 格式化时间日期(详见案例)
    • 法一 printf
    • 法二 printf(now.FOrmat(“2006-01-02 15:04:05”))
  5. 时间常量 :在程序中获得指定的时间单位的时间
const {
  Nanosecond Duration = 1 // 纳秒
  Microseond = 1000 * Nanosecond // 微妙
  Milliseond = 1000 * Microseond // 毫秒
  Second     = 1000 * Milliseond // 秒
  Minute     = 60 * Second //分
  Hour       = 60 * Minute  //时
}
  1. 休眠 Sleep()
  2. 获取当前unix时间戳和unixnano时间戳(用于获取随机数字)

二、案例解析

package main

import (
	"fmt"
	"time"
)

func main() {
	// 日期和时间相关函数和方法的使用

	// 1.获取当前时间
	now := time.Now()
	// now = 2022-10-16 12:33:25.9941447 +0800 CST m=+0.002308001, type = time.Time
	fmt.Printf("now = %v, type = %T", now, now)

	// 去除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())

	// 格式化时间
	fmt.Printf("当前年月日 %d-%d-%d %d:%d:%d \n", now.Year(),
		now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
	// 把字符串给一个变量
	dataStr := fmt.Sprintf("当前年月日 %d-%d-%d %d:%d:%d \n", now.Year(),
		now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())

	fmt.Printf("dataStr = %v", dataStr)

	// 格式化第二种写法
	// 2006/01/02 15:04:05 这个字符串是固定的,必须这样写
	// 数字不能乱改,间隔可以改
	// 可按需求组合
	fmt.Printf(now.Format("2006/01/02 15:04:05"))
	// 2022/10/16 14:38:34
	fmt.Println()
	fmt.Printf(now.Format("2006-01-02"))
	// 2022-10-16
	fmt.Println()
	fmt.Printf(now.Format("15:04:06"))
	// 14:38:22
	fmt.Println()

	// 只取月份
	fmt.Printf(now.Format("01"))
	fmt.Println()
	// 只取年
	fmt.Printf(now.Format("2006"))
	fmt.Println()

	// 时间的常量应用

	// // 结合Sleep使用
	// // 每个一秒打印一个数字,打印到100就退出
	// i := 0
	// for {
	// 	i++
	// 	fmt.Println("i = ", i)
	// 	//休眠
	// 	time.Sleep(time.Second)
	// 	if 1 == 100 {
	// 		break
	// 	}
	// }

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

	// Unix 和 UnixNano

	fmt.Printf("Unix 时间戳:=%v , UnixNano时间戳= %v\n", now.Unix(), now.UnixNano())
	// Unix 时间戳:=1665904263 , UnixNano时间戳= 1665904263830448500
	
}

三、最佳实践(统计函数执行时间)

package main

import (
	"fmt"
	"strconv"
	"time"
)

func test() {
	str := ""
	for i := 0; i < 100000; i++ {
		str += "hello" + strconv.Itoa(i)
	}
}

func main() {
	start := time.Now().Unix()

	test()

	end := time.Now().Unix()

	fmt.Printf("test函数执行时间为: %v", end-start)
}