25-Golang中的时间和日期函数

说明

在编程中,会经常使用到日期相关的函数,比如:统计某段代码执行花费的时间等等

基本用法

  • 1.time.Time类型,用于表示时间
  • 2.获取到当前时间的方法:now := time.Now // now的类型就是time.Time
package main
import (
	
	"fmt"
	"time"
)

func main() {
	now := time.Now()
	fmt.Printf("now=%v now type=%T", now, now)
}
//now=2023-01-08 21:46:04.0178332 +0800 CST m=+0.002207501 now type=time.Time  

3.获取到其他日期的信息

package main
import (
	
	"fmt"
	"time"
)

func main() {
	now := time.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("当前年月日 %02d-%02d-%02d %02d-%02d-%02d \n",
	now.Year(), now.Month(), now.Day(),
	now.Hour(), now.Minute(), now.Second())

	//格式化时间的第二种方式
	//"2006-01-02 15:04:05"这个字符串的各个数字是固定的,必须这样写
	//"2006-01-02 15:04:05"这个字符串各个数字可以自由的组合,可以按照程序需求返回时间和日期 
	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()

}

/*
年=2023
月=January
月=1
日=8
时=22
分=16
秒=55
当前年月日 2023-01-08 22-16-55
now.Format(2006-01-02 15:04:05)
now.Format(2006-01-02 )
now.Format(15:04:05)
*/
  • 4.时间的常量,作用:在程序中可用于获取指定时间单位的时间,比如得到100毫秒
    在这里插入图片描述
i := 0
	for {
		i++
		fmt.Println(i)
		//休眠
		time.Sleep(time.Second)
		if i == 20 {
			break
		}
	}
  • 5.获取当前Unix时间戳和unixnano时间戳(作用是可以获取随机数字)
fmt.Printf("unix时间戳=%v unixnano=%v", now.Unix(), now.UnixNano())
//unix时间戳=1673188257 unixnano=1673188257498223400

案例

获取一段代码的执行时间

package main
import (
	
	"fmt"
	"time"
	"strconv"
)

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

func main() {
	//在执行test前,先获取当前的unix时间戳
	start := time.Now().Unix()
	test()
	end := time.Now().Unix()
	fmt.Printf("执行test()耗费时间为%v秒\n", end-start)
}
/*
执行test()耗费时间为12秒
*/
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值