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()) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!