posts - 134,comments - 0,views - 66674

1、获取当前时间的方法

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

  

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

1
2
3
4
5
6
7
8
9
10
11
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")

1
2
3
4
5
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、时间的常量  

1
2
3
4
5
6
7
8
9
type Duration int64
const (
    Nanosecond  Duration = 1 // 纳秒
    Microsecond          = 1000 * Nanosecond // 微秒
    Millisecond          = 1000 * Microsecond // 毫秒
    Second               = 1000 * Millisecond // 秒
    Minute               = 60 * Second // 分钟
    Hour                 = 60 * Minute // 小时
)

  

5、休眠

1
time.Sleep(d Duration)

举例:

1
2
3
4
5
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时间戳(作用是可以获取随机数字)

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

举例:

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

  

posted on   smile学子  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示