本文介绍如何使用go根据某个时间节点获取时间范围

在业务逻辑上经常会有需要通过某一个时间节点获取该节点的时间范围,例如获取当前周,当前月份的数据,下面的代码是提取时间范围

代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 根据时间获取时间范围 周的开始和结束时间
func TimestampWeek(t time.Time) (start, end time.Time) {
	t = t.In(time.Local)
	st := t.AddDate(0, 0, -(int(t.Weekday() - 1)))
	start = time.Date(st.Year(), st.Month(), st.Day(), 0, 0, 0, 0, time.Local)
	et := t.AddDate(0, 0, 8-int(t.Weekday()))
	end = time.Date(et.Year(), et.Month(), et.Day(), 0, 0, 0, 0, time.Local)
	return
}

// 根据时间获取时间范围 日的开始和结束时间
func TimestampDay(t time.Time) (start, end time.Time) {
	t = t.In(time.Local)
	start = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)
	t = t.AddDate(0, 0, 1)
	end = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)
	return
}

// 根据时间获取时间范围 月的开始和结束时间
func TimestampMonth(t time.Time) (start, end time.Time) {
	t = t.In(time.Local)
	start = time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, time.Local)
	t = start.AddDate(0, 1, 0)
	end = time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, time.Local)
	return
}

// 根据时间获取时间范围 年的开始和结束时间
func TimestampYear(t time.Time) (start, end time.Time) {
	t = t.In(time.Local)
	start = time.Date(t.Year(), 1, 1, 0, 0, 0, 0, time.Local)
	t = start.AddDate(1, 0, 0)
	end = time.Date(t.Year(), 1, 1, 0, 0, 0, 0, time.Local)
	return
}

测试代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
func main() {
	now := time.Now()
	st, et := TimestampDay(now)
	fmt.Printf("now:%s\n", now.Format("2006-01-02 15:04:05"))
	fmt.Printf("TimestampDay start:%s end:%s\n", st.Format("2006-01-02 15:04:05"), et.Format("2006-01-02 15:04:05"))
	st, et = TimestampWeek(now)
	fmt.Printf("TimestampWeek start:%s end:%s\n", st.Format("2006-01-02 15:04:05"), et.Format("2006-01-02 15:04:05"))
	st, et = TimestampMonth(now)
	fmt.Printf("TimestampMonth start:%s end:%s\n", st.Format("2006-01-02 15:04:05"), et.Format("2006-01-02 15:04:05"))
	st, et = TimestampYear(now)
	fmt.Printf("TimestampYear start:%s end:%s\n", st.Format("2006-01-02 15:04:05"), et.Format("2006-01-02 15:04:05"))
}

输出结果

1
2
3
4
5
now:2023-08-10 18:55:07
TimestampDay start:2023-08-10 00:00:00 end:2023-08-11 00:00:00
TimestampWeek start:2023-08-07 00:00:00 end:2023-08-14 00:00:00
TimestampMonth start:2023-08-01 00:00:00 end:2023-09-01 00:00:00
TimestampYear start:2023-01-01 00:00:00 end:2024-01-01 00:00:00