Go的time包常见使用

1,575 阅读1分钟

记录平时项目中遇到的time包的使用方式。


// 根据时区获取当前时间
// 使用本地时区时间:timeStr2Time("2006-01-02 15:04:05", "2019-07-22 11:04:05", "")
// 使用指定时区时间:timeStr2Time("2006-01-02 15:04:05", "2019-07-22 11:04:05", "Asia/Shanghai")
func TimeStr2Time(fmtStr, valueStr, locStr string) time.Time {
	loc := time.Local
	if locStr != "" {
		loc, _ = time.LoadLocation(locStr)
	}
	tt, _ := time.ParseInLocation(fmtStr, valueStr, loc)
	return tt
}

// 获取当前时间戳
// GetCurrentSeds()
func GetCurrentSeds() int64 {
	return time.Now().Unix()
}

// 时间戳 to 时间字符串
// Seds2TimeStr(1563760410, "2006-01-02 15:04:05")
func Seds2TimeStr(seds int64, fmtStr string) string {
	return time.Unix(seds, 0).Format(fmtStr)
}

// 获取当前时间字符串
// GetCurrentTimeStr("2006-01-02 15:04:05")
func GetCurrentTimeStr(fmtStr string) string {
	return time.Now().Format(fmtStr)
}

// 将时间段转化为秒
// ParseDuration2Seds("1h")
func ParseDuration2Seds(du string) time.Duration {
	tp, err := time.ParseDuration(du)
	if err != nil {
		panic(err)
	}
	return tp
}

// 通过指定特定时区的特定时间点获取时间对象
// GetTimeByFmtDate((2018,1,2,15,30,10,0, time.Local)
func GetTimeByFmtDate(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time {
	return time.Date(year, month, day, hour, min, sec, nsec, loc)
}

// 时间计算-减法
//  func (t Time) Sub(u Time) Duration // 返回 Duraion
func CacuSub() {
	dt1 := time.Date(2018, 1, 10, 0, 0, 1, 100, time.Local)
	dt2 := time.Date(2018, 1, 9, 23, 59, 22, 100, time.Local)
	diff01 := dt1.Sub(dt2)           // 39s,带单位
	diff02 := dt1.Sub(dt2).Seconds() // 39,数值不带单位
	// 不用关注时区,go会转换成时间戳进行计算
	fmt.Println("diff =>", diff01, diff02)
}

// 时间计算-加法
// func (t Time) Add(d Duration) Time // 返回 Time
func CacuAdd() {
	now := time.Now()
	fmt.Println(now.Add(time.Duration(10) * time.Minute))
	fmt.Println(now.Add(10 * time.Minute))
}