golang学习笔记--日期函数

目录

【1】获取当前时间

【2】 格式化时间

【3】常用的时间常量

【4】获取时间戳


【1】获取当前时间

要使用日期相关的函数需要引入time包,Now()函数会返回当前本地时间,返回的是一个time.Time类型的结构体,里面内置了很多方法可以使用

package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()
	fmt.Println(now) // 2023-04-12 16:08:19.6984841 +0800 CST m=+0.002099101
	fmt.Printf("now的类型是%T", now) // now的类型是time.Time
}

【2】 格式化时间

方法一:较为繁琐

package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()
	fmt.Println(now)
	fmt.Printf("now的类型是%T\n", now)

	fmt.Printf("年 = %v\n", now.Year())
	fmt.Printf("月 = %v\n", now.Month())
	fmt.Printf("月 = %v\n", int(now.Month()))//使用int()将英文的月份转为数字
	fmt.Printf("日 = %v\n", now.Day())
	fmt.Printf("时 = %v\n", now.Hour())
	fmt.Printf("分 = %v\n", now.Minute())
	fmt.Printf("秒 = %v\n", now.Second())

	nowTime := fmt.Sprintf("%02d-%02d-%02d %02d:%02d:%02d", 
	now.Year(), now.Month(), now.Day(), 
	now.Hour(), now.Minute(), now.Second())
	
	fmt.Println(nowTime)
}

执行结果为

 

方法二:其中 2006  01  02     15   04    05 这些数字为固定写法 不可改变,可以简单记忆 6 1 2 3 4 5

package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()
	//获取当前格式化时间
	fmt.Println(now.Format("2006-01-02 15:04:05"))

	//获取当前年月日
	fmt.Println(now.Format("今天是2006年01月02日"))

	//获取当前几点钟
	fmt.Println(now.Format("当前时间是15点04分"))
}

输出结果为

【3】常用的时间常量

                Nanosecond  Duration  = 1 //纳秒
                Microsecond                 = 1000 * Nanosecond //微妙
                Millisecond                   = 1000 * Microsecond //毫秒
                Second                         = 1000 * Millisecond //秒
                Minute                          = 60 * Second //分钟
                Hour                             = 60 * Minute //小时

package main

import (
	"fmt"
	"time"
)

func main() {
	//时间常量
	/*
		const (
				Nanosecond  Duration = 1 //纳秒
				Microsecond          = 1000 * Nanosecond //微妙
				Millisecond          = 1000 * Microsecond //毫秒
				Second               = 1000 * Millisecond //秒
				Minute               = 60 * Second //分钟
				Hour                 = 60 * Minute //小时
			)
	
	*/
	//每隔0.1秒打印一个数字,到100停止
	i := 0
	for {
		i++
		fmt.Println(i)
		//休眠
		time.Sleep(time.Millisecond * 100) //使用毫秒 1秒=1000毫秒 所以乘100
		if i == 100 {
			break
		}
	}

}

【4】获取时间戳

时间戳就是获取从1970年1月1日 0点0分0秒开始到当前时间的秒数或毫秒数等

package main

import (
	"fmt"
	"time"
)

func main() {
	//unix 秒级时间戳
	sec := time.Now().Unix()
	fmt.Println(sec)

	//unix 毫秒级时间戳
	MilliSec := time.Now().UnixMilli()
	fmt.Println(MilliSec)

	//unix 微秒级时间戳
	MicroSec := time.Now().UnixMicro()
	fmt.Println(MicroSec)

	//unixnano 纳秒级时间戳
	nanoSec := time.Now().UnixNano()
	fmt.Println(nanoSec)
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值