golang时间相关函数总结

发布于:2025-02-23 ⋅ 阅读:(12) ⋅ 点赞:(0)
1.时间戳转换成日期函数
// 时间戳转换成日期函数
func UnixToTime(timestamp interface{}, format string) string {
	if format == "" {
		format = "2006-01-02 15:04:05"
	}
	value1, ok64 := timestamp.(int64) //类型断言,判断传入的参数数据类型,并根据不同数据类型进行逻辑处理
	value2, ok32 := timestamp.(int32)
	value3, ok := timestamp.(int)
	if ok64 {
		t := time.Unix(value1, 0)
		return t.Format(format)
	} else if ok32 {
		t := time.Unix(int64(value2), 0)
		return t.Format(format)
	} else if ok {
		t := time.Unix(int64(value3), 0)
		return t.Format(format)
	} else {
		return "time error"
	}
}
2.日期转换成时间戳 

// 日期转换成时间戳
func DateToUnix(str string) int64 {
	template := "2006-01-02 15:04:05"
	t, err := time.ParseInLocation(template, str, time.Local)
	if err != nil {
		return 0
	}
	return t.Unix()
}
3.获取当前时间戳 

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

// 获取当前时间戳(纳秒)
func GetUnixNano() int64 {
	return time.Now().UnixNano()
}
4.获取当前日期 
// 获取当前日期
func GetDate() string {
	template := "2006-01-02 15:04:05"
	return time.Now().Format(template)
}
5.获取年月日 
// 获取年月日
func GetDay() string {
	template := "20060102"
	return time.Now().Format(template)
}
6.计算当前时间到24点的秒数
// 计算当前时间到24点的秒数
func CalculateCurrentDay() time.Duration {
	// 获取当前时间
	now := time.Now()
	// 计算今天的午夜(24点)
	midnight := now.Truncate(24 * time.Hour).Add(24 * time.Hour)
	// 计算从当前时间到午夜的时间差
	duration := midnight.Sub(now)
	// 获取剩余的秒数
	seconds := int(duration.Seconds())
	return time.Duration(seconds)
}
7.获取起止日期时间戳
// 时间格式转换获取: 获取起止日期时间戳: eg: 2025-02-11 ~  2025-02-15, 需求获取2025-02-11 00:00:00 ~  2025-02-15 23:59:59 的时间戳范围
func GetDateRangeTimeStamp(startDate, endDate string) (startTimeStamp int64, endTimeStamp int64) {
	// 定义时间格式
	layout := "2006-01-02 15:04:05" // Go 中的时间格式必须是这个特定的值

	if startDate != "" { // 解析开始日期
		startDate = startDate + " 00:00:00"
		// 解析日期字符串为 time.Time 类型
		t, err := time.Parse(layout, startDate)
		if err != nil {
			panic(fmt.Sprintf("解析日期时出现错误:%s", err))
		}
		// 获取时间戳(秒)
		startTimeStamp = t.Unix()
	}

	if endDate != "" { // 解析截止日期
		endDate = endDate + " 23:59:59"
		// 解析日期字符串为 time.Time 类型
		t, err := time.Parse(layout, endDate)
		if err != nil {
			panic(fmt.Sprintf("解析日期时出现错误:%s", err))
		}
		// 获取时间戳(秒)
		endTimeStamp = t.Unix()
	}
	return startTimeStamp, endTimeStamp
}
8.获取近x日的开始结束时间戳

// 获取近x日的开始结束时间戳: eg: 获取近7日的开始结束时间戳
func GetUnixRangeByDays(days int64) (startUnix int64, endUnix int64) {
	// 获取当前时间
	now := time.Now()

	// 计算开始时间(7天前的今天的日期,不包括当前时间)
	startTime := now.AddDate(0, 0, -int(days)).Truncate(24 * time.Hour) // 向下取整到天的开始(00:00:00)

	// 计算结束时间(当前日期的结束时间)
	endTime := now.Truncate(24 * time.Hour).Add(24*time.Hour - time.Nanosecond) // 当前日期的结束(23:59:59)

	// 获取Unix时间戳
	startUnix = startTime.Unix()
	endUnix = endTime.Unix()

	return startUnix, endUnix
}