util.go 11 KB

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