需求
使用本地服务器对不同时区的客户发送日报,日报标题为当前时区的前一日(例:2月17日 日报)
依赖环境
- crontab linux定时任务
- go 1.18
- 服务器时区 东八区
实现思路
- 由于使用的是linux中的crobtab 来定时执行脚本,那么就没办法获取客户的实时时区,所以需要客户提前设定时区,以设定时区为准
- 独立同一个时区表示方式很多,例如东八区可以有很多种表现方式
Asia/Shanghai
Asia/Singapore
所以为了更方便筛选统一使用时间偏转+08:00
进行存储 - 定时脚本设定每一小时执行一次,执行时根据当前时间并通过客户设定时区获取为0时的时区偏转,通过该偏转筛选发送日报实体。
- 处理数据并按规则发送
代码
main.go
func main() {
// 根据东八区当前时间获取为0时的时区
timeZones := GetZeroTimeZone(time.Now().Hour())
// 获取上一小时 根据东八区当前时间获取为0时的时区
nextHour := GetZeroTimeZone(time.Now().Add(-time.Hour).Hour())
for _, timeZone := range timeZones {
// 获取时间范围兼容非整小时偏移时区
endTimeZone := timeZone
startTimeZone := nextHour[0]
if len(nextHour) == 2 {
startTimeZone = nextHour[1]
}
if startTimeZone > endTimeZone {
startTimeZone, endTimeZone = endTimeZone, startTimeZone
}
// 时间偏移数
offset := GetZeroTimeZoneToNumebr(timeZone)
// 偏移后的时区
cstZone := time.FixedZone("CST", offset*3600)
// 偏移后的时间
offsetTime := time.Now().In(cstZone)
// 日报标题
title := getTitleByDateConfig("day", offsetTime)
......日报内容处理
}
}
dateutil.go
// 0时区与东八区映射
func GetZeroTimeZone(hour int) (t []string) {
zeroMap := map[int][]string{
0: {"+08:00"},
1: {"+07:00"},
2: {"+06:00"},
3: {"+05:00"},
4: {"+04:00"},
5: {"+03:00"},
6: {"+02:00"},
7: {"+01:00"},
8: {"+00:00"},
9: {"-01:00"},
10: {"-02:00"},
11: {"-03:00"},
12: {"-04:00"},
13: {"-05:00"},
14: {"-06:00"},
15: {"-07:00"},
16: {"-08:00"},
17: {"-09:00"},
18: {"-10:00"},
19: {"-11:00"},
20: {"-12:00", "+12:00"},
21: {"+11:00"},
22: {"+10:00"},
23: {"+9:00"},
}
return zeroMap[hour]
}
// 时间偏移转小时
func GetZeroTimeZoneToNumebr(h string) (t int) {
r := 0
if strings.HasPrefix(h, "-") {
if string(h[4]) > "0" {
r -= 1
}
if string(h[1]) > "0" {
r -= 10
}
if string(h[2]) > "0" {
r -= cast.ToInt(string(h[2]))
}
}
if strings.HasPrefix(h, "+") {
if string(h[1]) > "0" {
r += 10
}
if string(h[2]) > "0" {
r += cast.ToInt(string(h[2]))
}
}
return r
}
// 日报标题生成
func getTitleByDateConfig(ReportType string, t time.Time) string {
var title string
if ReportType == "day" {
startTime := t.AddDate(0, 0, -1)
title = startTime.Format("日报 (01月02日)")
}
return title
}
备注
实现略粗糙,有更好实现方式欢迎讨论