util.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. package util
  2. import (
  3. "fmt"
  4. "math"
  5. "math/rand"
  6. "regexp"
  7. "time"
  8. "gitee.com/xuyiping_admin/pkg/xerr"
  9. )
  10. const (
  11. LayoutTime = "2006-01-02 15:04:05"
  12. Layout = "2006-01-02"
  13. LayoutMonth = "2006-01"
  14. LetterBytes = "abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789"
  15. LetterIdxBits = 6 // 6 bits to represent a letter index
  16. LetterIdxMask = 1<<LetterIdxBits - 1 // All 1-bits, as many as letterIdxBits
  17. LetterIdxMax = 63 / LetterIdxBits // # of letter indices fitting in 63 bits
  18. )
  19. // GenerateRandomNumberString 生成指定长度的数字串
  20. func GenerateRandomNumberString(n int) string {
  21. result := make([]byte, n)
  22. // A rand.Int63() generates 63 random bits, enough for letterIdxMax characters!
  23. rand.Seed(time.Now().UnixNano())
  24. for i, cache, remain := n-1, rand.Int63(), LetterIdxMax; i >= 0; {
  25. if remain == 0 {
  26. cache, remain = rand.Int63(), LetterIdxMax
  27. }
  28. if idx := int(cache & LetterIdxMask); idx < len(LetterBytes) {
  29. result[i] = LetterBytes[idx]
  30. i--
  31. }
  32. cache >>= LetterIdxBits
  33. remain--
  34. }
  35. return string(result)
  36. }
  37. // TimeParseLocalUnix 获取当天零点的时间戳
  38. // eg 2023-02-22 => 1676995200
  39. func TimeParseLocalUnix(DayTime string) int64 {
  40. value := DayTime
  41. if len(DayTime) <= 11 {
  42. value = fmt.Sprintf("%s 00:00:00", DayTime)
  43. }
  44. loc, _ := time.LoadLocation("Local")
  45. theTime, _ := time.ParseInLocation(LayoutTime, value, loc)
  46. return theTime.Unix()
  47. }
  48. // TimeParseLocalEndUnix 获取当天24点的时间戳
  49. // eg 2023-02-22 => 1676995200
  50. func TimeParseLocalEndUnix(DayTime string) int64 {
  51. value := DayTime
  52. if len(DayTime) <= 11 {
  53. value = fmt.Sprintf("%s 23:59:59", DayTime)
  54. }
  55. loc, _ := time.LoadLocation("Local")
  56. theTime, _ := time.ParseInLocation(LayoutTime, value, loc)
  57. return theTime.Unix()
  58. }
  59. // ConvertParseLocalUnix 字符串转换当天时间戳
  60. // eg 15:04:05 => 1676998245
  61. func ConvertParseLocalUnix(timeParse string) (int64, error) {
  62. loc, err := time.LoadLocation("Local")
  63. if err != nil {
  64. return 0, err
  65. }
  66. value := fmt.Sprintf("%s %s", time.Now().Format(Layout), timeParse)
  67. theTime, err := time.ParseInLocation(LayoutTime, value, loc)
  68. if err != nil {
  69. return 0, err
  70. }
  71. return theTime.Unix(), nil
  72. }
  73. // GetMonthRemainDay 获取当前月还剩几天
  74. func GetMonthRemainDay() int {
  75. now := time.Now()
  76. lastDayOfMonth := time.Date(now.Year(), now.Month()+1, 0, 23, 59, 59, 999999999, now.Location())
  77. return int(lastDayOfMonth.Sub(now).Hours()/24) + 1
  78. }
  79. // Ceil 向上取整函数
  80. func Ceil(x float64) float64 {
  81. // 使用 math.Floor 计算小于或等于 x 的最大整数
  82. // 然后检查 x 是否为整数,如果不是,则结果加 1
  83. // 注意:math.Floor 返回的是 float64 类型,所以我们需要进行比较
  84. // 来确定是否需要加 1
  85. intPart := math.Floor(x)
  86. if x-intPart > 0 {
  87. return intPart + 1
  88. }
  89. return intPart
  90. }
  91. // GetLastDayOfMonth
  92. // 接受一个字符串形式的月份(如 "2024-12"),
  93. // 并返回该月份的最后一天的日期(2024-12-31)
  94. func GetLastDayOfMonth(month string) (string, error) {
  95. t, err := time.Parse(LayoutMonth, month)
  96. if err != nil {
  97. return "", err // 如果解析失败,返回错误
  98. }
  99. // 获取下个月的第一天
  100. nextMonth := t.AddDate(0, 1, 0)
  101. // 返回上个月的最后一天
  102. lastDay := nextMonth.AddDate(0, 0, -1)
  103. return lastDay.Format(Layout), nil
  104. }
  105. // GetMonthsInRange
  106. // 接受两个字符串形式的月份(如 "2024-01" 到 "2024-12"),
  107. // 并返回一个包含这两个月份之间所有月份的字符串切片。
  108. func GetMonthsInRange(startMonth, endMonth string) ([]string, error) {
  109. // 解析起始月份
  110. startTime, err := time.Parse(LayoutMonth, startMonth)
  111. if err != nil {
  112. return nil, err
  113. }
  114. // 解析结束月份
  115. endTime, err := time.Parse(LayoutMonth, endMonth)
  116. if err != nil {
  117. return nil, err
  118. }
  119. // 初始化结果切片
  120. var months []string
  121. // 循环添加每个月份直到达到或超过结束月份
  122. for curr := startTime; curr.Before(endTime) || curr.Equal(endTime); curr = curr.AddDate(0, 1, 0) {
  123. months = append(months, curr.Format(LayoutMonth))
  124. }
  125. return months, nil
  126. }
  127. // RoundToTwoDecimals 四舍五入并保留两位小数
  128. func RoundToTwoDecimals(num float64) float64 {
  129. // 使用 math.Round 函数进行四舍五入
  130. // 先乘以 100,然后四舍五入,最后除以 100
  131. return math.Round(num*100) / 100
  132. }
  133. // Get21DayPeriods 获取范围时间内21天周期的切片
  134. // 从结束时间开始往前推算,超过开始时间,继续向前推算,直至凑整21天
  135. func Get21DayPeriods(startDay, endDay string) ([][]string, error) {
  136. startDate, err := time.Parse(Layout, startDay)
  137. if err != nil {
  138. return nil, err
  139. }
  140. endDate, err := time.Parse(Layout, endDay)
  141. if err != nil {
  142. return nil, err
  143. }
  144. if startDate.After(endDate) {
  145. return nil, xerr.Custom("start date is after end date")
  146. }
  147. var periods [][]string
  148. for date := endDate; date.After(startDate); {
  149. // Calculate the end of the current period
  150. periodEnd := date.AddDate(0, 0, -20)
  151. // Append the current period to the result slice
  152. periods = append(periods, []string{periodEnd.Format(Layout), date.Format(Layout)})
  153. // Move on to the next day
  154. date = periodEnd.AddDate(0, 0, -1)
  155. }
  156. reverseRows(periods)
  157. return periods, nil
  158. }
  159. func reverseRows(matrix [][]string) {
  160. // 获取矩阵的行数
  161. rows := len(matrix)
  162. if rows == 0 {
  163. return // 如果矩阵为空,则直接返回
  164. }
  165. // 初始化两个指针,一个指向开始,一个指向末尾
  166. for i, j := 0, rows-1; i < j; i, j = i+1, j-1 {
  167. // 交换当前行和对应行
  168. matrix[i], matrix[j] = matrix[j], matrix[i]
  169. }
  170. }
  171. // GetRangeDayMiddleDay 获取指定日期范围中间的某一天
  172. func GetRangeDayMiddleDay(dateRange []string, middleDay int32) (string, error) {
  173. if len(dateRange) < 2 {
  174. return "", xerr.Custom("date range is not enough")
  175. }
  176. if middleDay < 0 {
  177. return "", xerr.Custom("middle day is not enough")
  178. }
  179. startDate, _ := time.Parse(Layout, dateRange[0])
  180. return startDate.AddDate(0, 0, int(middleDay)-1).Format(Layout), nil
  181. }
  182. // GetRangeDayByDays 获取指定范围日期内按照指定天数来切割
  183. // (2024-10-01 ~ 2024-10-31,5)=> [[2024-10-01,2024-10-05], [2024-10-06,2024-10-10], [2024-10-11,2024-10-15], [2024-10-16,2024-10-20], [2024-10-21,2024-10-25], [2024-10-26,2024-10-30],[2024-10-31,2024-10-31]]
  184. func GetRangeDayByDays(startDay, endDay string, days int32) ([][]string, error) {
  185. var res [][]string
  186. if days <= 0 {
  187. return res, nil
  188. }
  189. startDate, err := time.Parse(Layout, startDay)
  190. if err != nil {
  191. return nil, err
  192. }
  193. endDate, err := time.Parse(Layout, endDay)
  194. if err != nil {
  195. return nil, err
  196. }
  197. if startDate.After(endDate) {
  198. return nil, xerr.Custom("start date is after end date")
  199. }
  200. if startDate == endDate {
  201. return [][]string{{startDay, endDay}}, nil
  202. }
  203. for date := startDate; date.Before(endDate) || date.Equal(endDate); date = date.AddDate(0, 0, int(days)) {
  204. if date.AddDate(0, 0, int(days)-1).After(endDate) {
  205. res = append(res, []string{date.Format(Layout), endDate.Format(Layout)})
  206. break
  207. }
  208. res = append(res, []string{date.Format(Layout), date.AddDate(0, 0, int(days)-1).Format(Layout)})
  209. }
  210. return res, nil
  211. }
  212. // 计算样本均值
  213. func mean(data []float64) float64 {
  214. sum := 0.0
  215. for _, v := range data {
  216. sum += v
  217. }
  218. return sum / float64(len(data))
  219. }
  220. // 计算样本标准差
  221. func stddev(data []float64, mean float64) float64 {
  222. sum := 0.0
  223. for _, v := range data {
  224. sum += (v - mean) * (v - mean)
  225. }
  226. variance := sum / float64(len(data)-1)
  227. return math.Sqrt(variance)
  228. }
  229. // ConfidenceInterval 计算95%置信区间
  230. func ConfidenceInterval(data []float64) (float64, float64) {
  231. n := float64(len(data))
  232. meanVal := mean(data)
  233. stdDev := stddev(data, meanVal)
  234. z := 1.96 // 95%置信水平对应的Z值
  235. marginOfError := z * (stdDev / math.Sqrt(n))
  236. lowerBound := meanVal - marginOfError
  237. upperBound := meanVal + marginOfError
  238. return lowerBound, upperBound
  239. }
  240. // ConfidenceInterval2 计算95%置信区间
  241. func ConfidenceInterval2(p float64, total float64) (min, max float64) {
  242. if p <= 0 || total <= 0 {
  243. return 0, 0
  244. }
  245. z := 1.96 // 95%置信水平对应的Z值
  246. marginOf := z * math.Sqrt(p*(1-p)/total) * 100
  247. return math.Max(0, p*100-math.Ceil(marginOf)), math.Max(1, p*100+math.Ceil(marginOf))
  248. }
  249. // RemoveDuplicates 去除切片中的重复元素
  250. func RemoveDuplicates(slice []string) []string {
  251. if len(slice) <= 0 {
  252. return slice
  253. }
  254. // 创建一个map来跟踪已经遇到的元素
  255. seen := make(map[string]struct{})
  256. // 创建一个新的切片来存储不重复的元素
  257. var result []string
  258. // 遍历原始切片
  259. for _, v := range slice {
  260. // 如果元素尚未在map中,则将其添加到结果切片和map中
  261. if _, exists := seen[v]; !exists {
  262. seen[v] = struct{}{}
  263. result = append(result, v)
  264. }
  265. }
  266. // 返回不重复的切片
  267. return result
  268. }
  269. func DaysBetween(startDayUnix int64, endDayUnix int64) int64 {
  270. time1 := time.Unix(startDayUnix, 0)
  271. time2 := time.Unix(endDayUnix, 0)
  272. // Truncate to the start of the day (00:00:00)
  273. startOfDay1 := time.Date(time1.Year(), time1.Month(), time1.Day(), 0, 0, 0, 0, time1.Location())
  274. startOfDay2 := time.Date(time2.Year(), time2.Month(), time2.Day(), 0, 0, 0, 0, time2.Location())
  275. // Calculate the difference in days
  276. daysDiff := int64(startOfDay2.Sub(startOfDay1).Hours() / 24)
  277. // Adjust sign if time2 is before time1
  278. if startOfDay2.Before(startOfDay1) {
  279. daysDiff = -daysDiff
  280. }
  281. return daysDiff
  282. }
  283. // MsgFormat 格式化消息字符串 字符串里面有多个冒号,仅删除冒号前后的空格(如果存在)
  284. func MsgFormat(input string) string {
  285. // 定义正则表达式,用于匹配冒号两边的空格
  286. re := regexp.MustCompile(`\s*:\s*`)
  287. // 使用正则表达式替换所有匹配的部分
  288. return re.ReplaceAllString(input, ":")
  289. }
  290. /*
  291. GetNeckRingActiveTimer
  292. 1. frameId值如果是:1到6代表每天的0点到2点,11-16 代表每天的2点到4点, 21-26 代表每天的4点到6点,31-36代表每天的6点到8点,
  293. 41-46 代表每天的8点到10点,51-56代表每天的10点到12点,61-66代表每天的12-14点,71-76代表每天的14-16点,81-86代表每天的16-18点,
  294. 91-96代表每天的18-20点,101-106代表每天的20-22点,111-116代表每天的22-24点。其中每天数字代表20分钟。如果frameId大于接受时间点,就代表frameId是昨天的。
  295. 2. 如果farmId取值出现8,18,28,3848,58,68,78,88,98,108,118数字分别代表2个小时,从0-2点开始,以此类推。
  296. 帮我根据frameId值,获取对应的时间点
  297. */
  298. func GetNeckRingActiveTimer(frameId int32) (dateTime string, hours int) {
  299. if frameId < 0 || frameId > 118 {
  300. return "", 0
  301. }
  302. nowTime := time.Now()
  303. currHour := nowTime.Hour()
  304. // 处理2小时的特殊 farmId
  305. specialHours := map[int]int{
  306. 8: 2, 18: 4, 28: 6, 38: 8, 48: 10, 58: 12, 68: 14, 78: 16, 88: 18, 98: 20, 108: 22, 118: 0,
  307. }
  308. hours, ok := specialHours[int(frameId)]
  309. day := 0
  310. if ok {
  311. if hours > currHour {
  312. day = -1
  313. }
  314. dateTime = nowTime.AddDate(0, 0, day).Format(Layout)
  315. return
  316. }
  317. hours = int(math.Floor(float64(frameId)/10) * 2)
  318. units := int(frameId % 10)
  319. hours += units / 3
  320. if hours > currHour {
  321. day = -1
  322. }
  323. dateTime = nowTime.AddDate(0, 0, day).Format(Layout)
  324. return
  325. }