go语言基础 --时间处理常用函数

获取当前时间

时间和日期相关的函数是开发中常用的,go语言中,引入time包即可使用相关的函数

  1. 获取当前时间的方法:time.Now(),返回一个time.Time类型的时间信息,可直接打印出来
go 复制代码
func main() {
    now := time.Now()
    fmt.Printf("%v, %T", now, now)
}

单独获取年月日时分秒

go 复制代码
package main
import(
    "fmt"
)
func main() {
    now := time.Now()
    fmt.Printf("%v, %T\n", now, now)
    fmt.Printf("%v, %T\n", now.Year(), now.Year())
    fmt.Printf("%v, %T\n", now.Year(), now.Year())
    fmt.Printf("%v, %T\n", now.Month(), now.Month())
    fmt.Printf("%v, %T\n", now.Day(), now.Day())
    fmt.Printf("%v, %T\n", now.Hour(), now.Hour())
    fmt.Printf("%v, %T\n", now.Minute(), now.Minute())
    fmt.Printf("%v, %T\n", now.Second(), now.Second())
}

输出如下

这里的月分是time.Month,如果想用int,可以用int(month)进行强转

日期格式化

go 复制代码
// 方法1,使用Printf/Sprintf
fmt.Printf("%02d-%02d-%02d %02d-%02d-%0d2", 
    now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
// 方法2,使用Format()函数
fmt.Printf(now.Format("2006/01/02 15:04:05"))
fmt.Printf(now.Format("2006-01-02"))
fmt.Printf(now.Format("15:04:05"))
// 这里的2006/01/02 15:04:05是指定格式,固定的字符串,不可变更,据说是go语言创建之初的时间
// 如果值想取月,只保留01,只想取日,保留02,以此类推

时间常量

go 复制代码
const(
    Nanosecond
    Microsecond
    Millisecond
    Second
    Minute
    Hour
)

常用在延时场景,如

go 复制代码
time.Sleep(100 * Nanosecond)

获取当前unix时间戳和nano时间戳

时间戳有时用于生成随机数或前后端时间传递,我们可以使用time的Unix和UnixNano方法,Unix方法返回自1970年1月1日00:00:00的总秒数,UnixNano返回总纳秒数

go 复制代码
// 注意这里参数t写在前面,表示这个是个只能在Time类型中使用的方法
func (t Time) Unix() int64
func (t Time) UnixNano() int64
相关推荐
追逐时光者1 小时前
精选 4 款基于 .NET 开源、功能强大的 Windows 系统优化工具
后端·.net
TF男孩1 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
AAA修煤气灶刘哥2 小时前
别让Redis「歪脖子」!一次搞定数据倾斜与请求倾斜的捉妖记
redis·分布式·后端
AAA修煤气灶刘哥2 小时前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
你的人类朋友3 小时前
什么是API签名?
前端·后端·安全
昵称为空C5 小时前
SpringBoot3 http接口调用新方式RestClient + @HttpExchange像使用Feign一样调用
spring boot·后端
架构师沉默5 小时前
设计多租户 SaaS 系统,如何做到数据隔离 & 资源配额?
java·后端·架构
RoyLin5 小时前
TypeScript设计模式:适配器模式
前端·后端·node.js
该用户已不存在6 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
Moonbit6 小时前
MoonBit 正式加入 WebAssembly Component Model 官方文档 !
前端·后端·编程语言