Go中的时间处理
Go的时间相关API操作在日常的开发中经常用到,下面进行总结汇总。
- 获取当前的时间相关
now := time.Now()
fmt.Println(now.Year()) // 获取年份
fmt.Println(now.Month()) // 获取月份
fmt.Println(now.Day()) // 获取天日期
fmt.Println(now.Hour()) // 获取小时
fmt.Println(now.Minute()) // 获取分钟
fmt.Println(now.Second()) // 获取秒
fmt.Println(now.Unix()) // 获取时间戳
fmt.Println(now.UnixMilli()) // 获取毫秒时间戳
fmt.Println(now.UnixMicro()) // 获取微秒时间戳
fmt.Println(now.UnixNano()) // 获取纳秒时间戳
fmt.Println(now.UTC()) // 获取UTC时间
fmt.Println(now.Weekday()) // 获取星期
fmt.Println(now.YearDay()) // 获取当前是一年中的第几天
fmt.Println(now.Location()) // 获取
fmt.Println(now.Local()) // 获取服务器时间
fmt.Println(now.Clock()) // 获取几点几分几秒
fmt.Println(now.Date()) // 获取年、月、日
fmt.Println(now.Format("2006-01-02 15:03:04")) // 时间格式化
fmt.Println(now.Format("2006.01.02"))
fmt.Println(now.Format("15:03:04"))
- 字符串时间转化为时间
t, _ := time.Parse("2006-01-02 15:04:05", "2021-01-10 15:01:02") // 字符串转时间
fmt.Println(t)
str := time.Now().Format("2006-01-02 15:04:05") // 获取string格式当前时间
t, _ := time.ParseInLocation("2006-01-02 15:04:05", str, time.Local) // 指定本地时区
fmt.Println(t)
// 获取当天0时时间戳
func Today() int64 {
today, _ := time.Parse("2006-01-02 00:00:00", time.Now().Format("2006-01-02 00:00:00"))
return today.UnixMilli()
}
// 获取昨天0时时间戳
func Yesterday() int64 {
today, _ := time.Parse("2006-01-02 00:00:00", time.Now().AddDate(0, 0, -1).Format("2006-01-02 00:00:00"))
return today.UnixMilli()
}
// 将指定时间戳转换为对应时间字符串
tm := time.UnixMilli(1678665600000).Format("2006-01-02")
fmt.Println(tm)
- 时间的增减
now := time.Now()
now.AddDate(1, 1, 1)
- 日期比较
func (t Time) Before(u Time) bool // 如果 t 代表的时间点在 u 之前,返回真;否则返回假。
func (t Time) After(u Time) bool // 如果 t 代表的时间点在 u 之后,返回真;否则返回假。
func (t Time) Equal(u Time) bool // 比较时间是否相等,相等返回真;否则返回假。
time.Since(now) // 计算程序的间隔时间差