common.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378
  1. package utils
  2. import (
  3. "bufio"
  4. "crypto/cipher"
  5. "crypto/des"
  6. "crypto/md5"
  7. "crypto/sha1"
  8. "encoding/base64"
  9. "encoding/hex"
  10. "encoding/json"
  11. "errors"
  12. "fmt"
  13. "image"
  14. "image/png"
  15. "io"
  16. "math"
  17. "math/rand"
  18. "net"
  19. "net/http"
  20. "os"
  21. "os/exec"
  22. "path"
  23. "regexp"
  24. "strconv"
  25. "strings"
  26. "time"
  27. "github.com/shopspring/decimal"
  28. )
  29. // 随机数种子
  30. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  31. func GetRandString(size int) string {
  32. allLetterDigit := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "!", "@", "#", "$", "%", "^", "&", "*"}
  33. randomSb := ""
  34. digitSize := len(allLetterDigit)
  35. for i := 0; i < size; i++ {
  36. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  37. }
  38. return randomSb
  39. }
  40. func GetRandStringNoSpecialChar(size int) string {
  41. allLetterDigit := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
  42. randomSb := ""
  43. digitSize := len(allLetterDigit)
  44. for i := 0; i < size; i++ {
  45. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  46. }
  47. return randomSb
  48. }
  49. func StringsToJSON(str string) string {
  50. rs := []rune(str)
  51. jsons := ""
  52. for _, r := range rs {
  53. rint := int(r)
  54. if rint < 128 {
  55. jsons += string(r)
  56. } else {
  57. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  58. }
  59. }
  60. return jsons
  61. }
  62. // 序列化
  63. func ToString(v interface{}) string {
  64. data, _ := json.Marshal(v)
  65. return string(data)
  66. }
  67. // md5加密
  68. func MD5(data string) string {
  69. m := md5.Sum([]byte(data))
  70. return hex.EncodeToString(m[:])
  71. }
  72. // 获取数字随机字符
  73. func GetRandDigit(n int) string {
  74. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  75. }
  76. // 获取随机数
  77. func GetRandNumber(n int) int {
  78. return rnd.Intn(n)
  79. }
  80. func GetRandInt(min, max int) int {
  81. if min >= max || min == 0 || max == 0 {
  82. return max
  83. }
  84. return rand.Intn(max-min) + min
  85. }
  86. func GetToday(format string) string {
  87. today := time.Now().Format(format)
  88. return today
  89. }
  90. // 获取今天剩余秒数
  91. func GetTodayLastSecond() time.Duration {
  92. today := GetToday(FormatDate) + " 23:59:59"
  93. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  94. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  95. }
  96. // 处理出生日期函数
  97. func GetBrithDate(idcard string) string {
  98. l := len(idcard)
  99. var s string
  100. if l == 15 {
  101. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  102. return s
  103. }
  104. if l == 18 {
  105. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  106. return s
  107. }
  108. return GetToday(FormatDate)
  109. }
  110. // 处理性别
  111. func WhichSexByIdcard(idcard string) string {
  112. var sexs = [2]string{"女", "男"}
  113. length := len(idcard)
  114. if length == 18 {
  115. sex, _ := strconv.Atoi(string(idcard[16]))
  116. return sexs[sex%2]
  117. } else if length == 15 {
  118. sex, _ := strconv.Atoi(string(idcard[14]))
  119. return sexs[sex%2]
  120. }
  121. return "男"
  122. }
  123. // 截取小数点后几位
  124. func SubFloatToString(f float64, m int) string {
  125. n := strconv.FormatFloat(f, 'f', -1, 64)
  126. if n == "" {
  127. return ""
  128. }
  129. if m >= len(n) {
  130. return n
  131. }
  132. newn := strings.Split(n, ".")
  133. if m == 0 {
  134. return newn[0]
  135. }
  136. if len(newn) < 2 || m >= len(newn[1]) {
  137. return n
  138. }
  139. return newn[0] + "." + newn[1][:m]
  140. }
  141. // 截取小数点后几位
  142. func SubFloatToFloat(f float64, m int) float64 {
  143. newn := SubFloatToString(f, m)
  144. newf, _ := strconv.ParseFloat(newn, 64)
  145. return newf
  146. }
  147. // 截取小数点后几位
  148. func SubFloatToFloatStr(f float64, m int) string {
  149. newn := SubFloatToString(f, m)
  150. return newn
  151. }
  152. // 获取相差时间-年
  153. func GetYearDiffer(start_time, end_time string) int {
  154. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  155. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  156. age := t2.Year() - t1.Year()
  157. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  158. age--
  159. }
  160. return age
  161. }
  162. // 获取相差时间-秒
  163. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  164. diff := end_time.Unix() - start_time.Unix()
  165. return diff
  166. }
  167. func FixFloat(f float64, m int) float64 {
  168. newn := SubFloatToString(f+0.00000001, m)
  169. newf, _ := strconv.ParseFloat(newn, 64)
  170. return newf
  171. }
  172. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  173. func StrListToString(strList []string) (str string) {
  174. if len(strList) > 0 {
  175. for k, v := range strList {
  176. if k == 0 {
  177. str = v
  178. } else {
  179. str = str + "," + v
  180. }
  181. }
  182. return
  183. }
  184. return ""
  185. }
  186. // 数据没有记录
  187. func ErrNoRow() string {
  188. return "<QuerySeter> no row found"
  189. }
  190. // 校验邮箱格式
  191. func ValidateEmailFormatat(email string) bool {
  192. reg := regexp.MustCompile(RegularEmail)
  193. return reg.MatchString(email)
  194. }
  195. // 验证是否是手机号
  196. func ValidateMobileFormatat(mobileNum string) bool {
  197. reg := regexp.MustCompile(RegularMobile)
  198. return reg.MatchString(mobileNum)
  199. }
  200. // 判断文件是否存在
  201. func FileIsExist(filePath string) bool {
  202. _, err := os.Stat(filePath)
  203. return err == nil || os.IsExist(err)
  204. }
  205. // 获取图片扩展名
  206. func GetImgExt(file string) (ext string, err error) {
  207. var headerByte []byte
  208. headerByte = make([]byte, 8)
  209. fd, err := os.Open(file)
  210. if err != nil {
  211. return "", err
  212. }
  213. defer fd.Close()
  214. _, err = fd.Read(headerByte)
  215. if err != nil {
  216. return "", err
  217. }
  218. xStr := fmt.Sprintf("%x", headerByte)
  219. switch {
  220. case xStr == "89504e470d0a1a0a":
  221. ext = ".png"
  222. case xStr == "0000010001002020":
  223. ext = ".ico"
  224. case xStr == "0000020001002020":
  225. ext = ".cur"
  226. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  227. ext = ".gif"
  228. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  229. ext = ".tga"
  230. case xStr[:8] == "464f524d":
  231. ext = ".iff"
  232. case xStr[:8] == "52494646":
  233. ext = ".ani"
  234. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  235. ext = ".tiff"
  236. case xStr[:4] == "424d":
  237. ext = ".bmp"
  238. case xStr[:4] == "ffd8":
  239. ext = ".jpg"
  240. case xStr[:2] == "0a":
  241. ext = ".pcx"
  242. default:
  243. ext = ""
  244. }
  245. return ext, nil
  246. }
  247. // 保存图片
  248. func SaveImage(path string, img image.Image) (err error) {
  249. //需要保持的文件
  250. imgfile, err := os.Create(path)
  251. defer imgfile.Close()
  252. // 以PNG格式保存文件
  253. err = png.Encode(imgfile, img)
  254. return err
  255. }
  256. // 下载图片
  257. func DownloadImage(imgUrl string) (filePath string, err error) {
  258. imgPath := "./static/imgs/"
  259. fileName := path.Base(imgUrl)
  260. res, err := http.Get(imgUrl)
  261. if err != nil {
  262. fmt.Println("A error occurred!")
  263. return
  264. }
  265. defer res.Body.Close()
  266. // 获得get请求响应的reader对象
  267. reader := bufio.NewReaderSize(res.Body, 32*1024)
  268. filePath = imgPath + fileName
  269. file, err := os.Create(filePath)
  270. if err != nil {
  271. return
  272. }
  273. // 获得文件的writer对象
  274. writer := bufio.NewWriter(file)
  275. written, _ := io.Copy(writer, reader)
  276. fmt.Printf("Total length: %d \n", written)
  277. return
  278. }
  279. // 保存base64数据为文件
  280. func SaveBase64ToFile(content, path string) error {
  281. data, err := base64.StdEncoding.DecodeString(content)
  282. if err != nil {
  283. return err
  284. }
  285. f, err := os.Create(path)
  286. defer f.Close()
  287. if err != nil {
  288. return err
  289. }
  290. f.Write(data)
  291. return nil
  292. }
  293. func SaveBase64ToFileBySeek(content, path string) (err error) {
  294. data, err := base64.StdEncoding.DecodeString(content)
  295. exist, err := PathExists(path)
  296. if err != nil {
  297. return
  298. }
  299. if !exist {
  300. f, err := os.Create(path)
  301. if err != nil {
  302. return err
  303. }
  304. n, _ := f.Seek(0, 2)
  305. // 从末尾的偏移量开始写入内容
  306. _, err = f.WriteAt([]byte(data), n)
  307. defer f.Close()
  308. } else {
  309. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  310. if err != nil {
  311. return err
  312. }
  313. n, _ := f.Seek(0, 2)
  314. // 从末尾的偏移量开始写入内容
  315. _, err = f.WriteAt([]byte(data), n)
  316. defer f.Close()
  317. }
  318. return nil
  319. }
  320. func PathExists(path string) (bool, error) {
  321. _, err := os.Stat(path)
  322. if err == nil {
  323. return true, nil
  324. }
  325. if os.IsNotExist(err) {
  326. return false, nil
  327. }
  328. return false, err
  329. }
  330. func StartIndex(page, pagesize int) int {
  331. if page > 1 {
  332. return (page - 1) * pagesize
  333. }
  334. return 0
  335. }
  336. func PageCount(count, pagesize int) int {
  337. if count%pagesize > 0 {
  338. return count/pagesize + 1
  339. } else {
  340. return count / pagesize
  341. }
  342. }
  343. func TrimHtml(src string) string {
  344. //将HTML标签全转换成小写
  345. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  346. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  347. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  348. src = re.ReplaceAllString(src, "[图片]")
  349. re, _ = regexp.Compile("class[\\S\\s]+?>")
  350. src = re.ReplaceAllString(src, "")
  351. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  352. src = re.ReplaceAllString(src, "")
  353. return strings.TrimSpace(src)
  354. }
  355. //1556164246 -> 2019-04-25 03:50:46 +0000
  356. //timestamp
  357. func TimeToTimestamp() {
  358. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  359. }
  360. func ToUnicode(text string) string {
  361. textQuoted := strconv.QuoteToASCII(text)
  362. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  363. return textUnquoted
  364. }
  365. func VersionToInt(version string) int {
  366. version = strings.Replace(version, ".", "", -1)
  367. n, _ := strconv.Atoi(version)
  368. return n
  369. }
  370. func IsCheckInList(list []int, s int) bool {
  371. for _, v := range list {
  372. if v == s {
  373. return true
  374. }
  375. }
  376. return false
  377. }
  378. func round(num float64) int {
  379. return int(num + math.Copysign(0.5, num))
  380. }
  381. func toFixed(num float64, precision int) float64 {
  382. output := math.Pow(10, float64(precision))
  383. return float64(round(num*output)) / output
  384. }
  385. // GetWilsonScore returns Wilson Score
  386. func GetWilsonScore(p, n float64) float64 {
  387. if p == 0 && n == 0 {
  388. return 0
  389. }
  390. return toFixed(((p+1.9208)/(p+n)-1.96*math.Sqrt(p*n/(p+n)+0.9604)/(p+n))/(1+3.8416/(p+n)), 2)
  391. }
  392. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  393. func ChangeWordsToNum(str string) (numStr string) {
  394. words := ([]rune)(str)
  395. num := 0
  396. n := 0
  397. for i := 0; i < len(words); i++ {
  398. word := string(words[i : i+1])
  399. switch word {
  400. case "万":
  401. if n == 0 {
  402. n = 1
  403. }
  404. n = n * 10000
  405. num = num*10000 + n
  406. n = 0
  407. case "千":
  408. if n == 0 {
  409. n = 1
  410. }
  411. n = n * 1000
  412. num += n
  413. n = 0
  414. case "百":
  415. if n == 0 {
  416. n = 1
  417. }
  418. n = n * 100
  419. num += n
  420. n = 0
  421. case "十":
  422. if n == 0 {
  423. n = 1
  424. }
  425. n = n * 10
  426. num += n
  427. n = 0
  428. case "一":
  429. n += 1
  430. case "二":
  431. n += 2
  432. case "三":
  433. n += 3
  434. case "四":
  435. n += 4
  436. case "五":
  437. n += 5
  438. case "六":
  439. n += 6
  440. case "七":
  441. n += 7
  442. case "八":
  443. n += 8
  444. case "九":
  445. n += 9
  446. case "零":
  447. default:
  448. if n > 0 {
  449. num += n
  450. n = 0
  451. }
  452. if num == 0 {
  453. numStr += word
  454. } else {
  455. numStr += strconv.Itoa(num) + word
  456. num = 0
  457. }
  458. }
  459. }
  460. if n > 0 {
  461. num += n
  462. n = 0
  463. }
  464. if num != 0 {
  465. numStr += strconv.Itoa(num)
  466. }
  467. return
  468. }
  469. func Sha1(data string) string {
  470. sha1 := sha1.New()
  471. sha1.Write([]byte(data))
  472. return hex.EncodeToString(sha1.Sum([]byte("")))
  473. }
  474. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  475. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  476. out, err := exec.Command("bash", "-c", cmd).Output()
  477. if err != nil {
  478. return
  479. }
  480. outTimes := string(out)
  481. fmt.Println("outTimes:", outTimes)
  482. if outTimes != "" {
  483. timeArr := strings.Split(outTimes, ":")
  484. h := timeArr[0]
  485. m := timeArr[1]
  486. s := timeArr[2]
  487. hInt, err := strconv.Atoi(h)
  488. if err != nil {
  489. return playSeconds, err
  490. }
  491. mInt, err := strconv.Atoi(m)
  492. if err != nil {
  493. return playSeconds, err
  494. }
  495. s = strings.Trim(s, " ")
  496. s = strings.Trim(s, "\n")
  497. sInt, err := strconv.ParseFloat(s, 64)
  498. if err != nil {
  499. return playSeconds, err
  500. }
  501. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  502. }
  503. return
  504. }
  505. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  506. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  507. tradeCode = strings.Trim(tradeCode, " ")
  508. tradeCodeInt, err := strconv.Atoi(tradeCode)
  509. if err != nil {
  510. return
  511. }
  512. tradeCodeInt = tradeCodeInt + 1
  513. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  514. return
  515. }
  516. // excel日期字段格式化 yyyy-mm-dd
  517. func ConvertToFormatDay(excelDaysString string) string {
  518. // 2006-01-02 距离 1900-01-01的天数
  519. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  520. curDiffDay := excelDaysString
  521. b, _ := strconv.Atoi(curDiffDay)
  522. // 获取excel的日期距离2006-01-02的天数
  523. realDiffDay := b - baseDiffDay
  524. //fmt.Println("realDiffDay:",realDiffDay)
  525. // 距离2006-01-02 秒数
  526. realDiffSecond := realDiffDay * 24 * 3600
  527. //fmt.Println("realDiffSecond:",realDiffSecond)
  528. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  529. baseOriginSecond := 1136185445
  530. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  531. return resultTime
  532. }
  533. func CheckPwd(pwd string) bool {
  534. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  535. reg := regexp.MustCompile(compile)
  536. flag := reg.MatchString(pwd)
  537. return flag
  538. }
  539. func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
  540. // 数字月份必须前置补零
  541. if len(myMonth) == 1 {
  542. myMonth = "0" + myMonth
  543. }
  544. yInt, _ := strconv.Atoi(myYear)
  545. timeLayout := "2006-01-02 15:04:05"
  546. loc, _ := time.LoadLocation("Local")
  547. theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
  548. newMonth := theTime.Month()
  549. t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  550. t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  551. return t1, t2
  552. }
  553. // 移除字符串中的空格
  554. func TrimStr(str string) (str2 string) {
  555. return strings.Replace(str, " ", "", -1)
  556. }
  557. // 字符串转换为time
  558. func StrTimeToTime(strTime string) time.Time {
  559. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  560. loc, _ := time.LoadLocation("Local") //重要:获取时区
  561. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  562. return resultTime
  563. }
  564. // GetOrmInReplace 获取orm的in查询替换?的方法
  565. func GetOrmInReplace(num int) string {
  566. template := make([]string, num)
  567. for i := 0; i < num; i++ {
  568. template[i] = "?"
  569. }
  570. return strings.Join(template, ",")
  571. }
  572. // RevSlice 反转切片
  573. func RevSlice(slice []int) []int {
  574. for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
  575. slice[i], slice[j] = slice[j], slice[i]
  576. }
  577. return slice
  578. }
  579. // GetTimeSubDay 计算两个时间的自然日期差
  580. func GetTimeSubDay(t1, t2 time.Time) int {
  581. var day int
  582. swap := false
  583. if t1.Unix() > t2.Unix() {
  584. t1, t2 = t2, t1
  585. swap = true
  586. }
  587. t1_ := t1.Add(time.Duration(t2.Sub(t1).Milliseconds()%86400000) * time.Millisecond)
  588. day = int(t2.Sub(t1).Hours() / 24)
  589. // 计算在t1+两个时间的余数之后天数是否有变化
  590. if t1_.Day() != t1.Day() {
  591. day += 1
  592. }
  593. if swap {
  594. day = -day
  595. }
  596. return day
  597. }
  598. // GetDaysBetween2Date 计算两个日期之间相差几天
  599. func GetDaysBetween2Date(format, date1Str, date2Str string) (int, error) {
  600. // 将字符串转化为Time格式
  601. date1, err := time.ParseInLocation(format, date1Str, time.Local)
  602. if err != nil {
  603. return 0, err
  604. }
  605. // 将字符串转化为Time格式
  606. date2, err := time.ParseInLocation(format, date2Str, time.Local)
  607. if err != nil {
  608. return 0, err
  609. }
  610. //计算相差天数
  611. return int(date1.Sub(date2).Hours() / 24), nil
  612. }
  613. // MapSorter 对于map 排序
  614. type MapSorter []Item
  615. type Item struct {
  616. Key int
  617. Val float64
  618. }
  619. func NewMapSorter(m map[int]float64) MapSorter {
  620. ms := make(MapSorter, 0, len(m))
  621. for k, v := range m {
  622. ms = append(ms, Item{k, v})
  623. }
  624. return ms
  625. }
  626. func (ms MapSorter) Len() int {
  627. return len(ms)
  628. }
  629. func (ms MapSorter) Less(i, j int) bool {
  630. return ms[i].Val > ms[j].Val // 按值排序
  631. //return ms[i].Key < ms[j].Key // 按键排序
  632. }
  633. func (ms MapSorter) Swap(i, j int) {
  634. ms[i], ms[j] = ms[j], ms[i]
  635. }
  636. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  637. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  638. for _, id := range idIntList {
  639. if id == searchId {
  640. has = true
  641. return
  642. }
  643. }
  644. return
  645. }
  646. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  647. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  648. for _, id := range idStrList {
  649. if id == searchId {
  650. has = true
  651. return
  652. }
  653. }
  654. return
  655. }
  656. // GetDateByDateType 通过dateType获取需要的开始/结束日期
  657. func GetDateByDateType(dateType int, tmpStartDate, tmpEndDate string) (startDate, endDate string) {
  658. startDate = tmpStartDate
  659. endDate = tmpEndDate
  660. switch dateType {
  661. case 1:
  662. startDate = "2000-01-01"
  663. endDate = ""
  664. case 2:
  665. startDate = "2010-01-01"
  666. endDate = ""
  667. case 3:
  668. startDate = "2015-01-01"
  669. endDate = ""
  670. case 4:
  671. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  672. startDate = "2021-01-01"
  673. endDate = ""
  674. case 5:
  675. //startDate = startDate + "-01"
  676. //endDate = endDate + "-01"
  677. case 6:
  678. //startDate = startDate + "-01"
  679. endDate = ""
  680. case 7:
  681. startDate = "2018-01-01"
  682. endDate = ""
  683. case 8:
  684. startDate = "2019-01-01"
  685. endDate = ""
  686. case 9:
  687. startDate = "2020-01-01"
  688. endDate = ""
  689. case 11:
  690. startDate = "2022-01-01"
  691. endDate = ""
  692. }
  693. // 兼容日期错误
  694. {
  695. if strings.Count(startDate, "-") == 1 {
  696. startDate = startDate + "-01"
  697. }
  698. if strings.Count(endDate, "-") == 1 {
  699. endDate = endDate + "-01"
  700. }
  701. }
  702. return
  703. }
  704. // GetDateByDateType2 通过dateType获取需要的开始/结束日期(日期类型:1:最近3月;2:最近6月;3:最近1年;4:最近2年;5:最近3年;6:最近5年;7:最近10年,8:自定义时间)
  705. func GetDateByDateType2(dateType int, currDate time.Time) (startDate time.Time) {
  706. switch dateType {
  707. case 1:
  708. startDate = currDate.AddDate(0, -3, 0)
  709. case 2:
  710. startDate = currDate.AddDate(0, -6, 0)
  711. case 3:
  712. startDate = currDate.AddDate(-1, 0, 0)
  713. case 4:
  714. startDate = currDate.AddDate(-2, 0, 0)
  715. case 5:
  716. startDate = currDate.AddDate(-3, 0, 0)
  717. case 6:
  718. startDate = currDate.AddDate(-5, 0, 0)
  719. case 7:
  720. startDate = currDate.AddDate(-10, 0, 0)
  721. }
  722. return
  723. }
  724. // GetCeilNewNum 保留n位有效数字的向上取整
  725. // @params num 实际数据
  726. // @params baseLen 需要保留的有效位数
  727. func GetCeilNewNum(num float64, baseLen int) (newNum float64) {
  728. if num >= 1 {
  729. tmpNum := int(math.Ceil(num)) // 向上取整
  730. str := strconv.Itoa(tmpNum)
  731. lenStr := len(str)
  732. if lenStr > baseLen {
  733. newNumStr := str[0:baseLen]
  734. newNumInt, _ := strconv.Atoi(newNumStr)
  735. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  736. if newNum < num {
  737. newNumInt += 1
  738. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  739. }
  740. } else {
  741. newNum = float64(tmpNum)
  742. }
  743. return
  744. } else if num > 0 {
  745. // 这是小数
  746. str := strconv.FormatFloat(num, 'f', -1, 64)
  747. // 去除小数点和负号
  748. str = removeDecimalPoint(str)
  749. // 计算字符串长度
  750. lenStr := len(str)
  751. if lenStr > baseLen {
  752. newNumStr := str[0:baseLen]
  753. newNumInt, _ := strconv.Atoi(newNumStr)
  754. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  755. if newNum < num {
  756. newNumInt += 1
  757. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  758. }
  759. } else {
  760. newNum = num
  761. }
  762. } else if num > -1 {
  763. // 这是小数
  764. str := strconv.FormatFloat(num, 'f', -1, 64)
  765. // 去除小数点和负号
  766. str = removeDecimalPoint(str)
  767. // 计算字符串长度
  768. lenStr := len(str)
  769. if lenStr > baseLen {
  770. newNumStr := str[0:baseLen]
  771. newNumInt, _ := strconv.Atoi(newNumStr)
  772. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  773. newNum = -newNum
  774. if newNum < num {
  775. newNumInt -= 1
  776. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  777. newNum = -newNum
  778. }
  779. } else {
  780. newNum = num
  781. }
  782. if newNum == -0 {
  783. newNum = 0
  784. }
  785. } else { // 小于等于-1
  786. tmpNumFloat := math.Abs(num)
  787. tmpNum := int(math.Floor(tmpNumFloat)) // 向上取整
  788. str := strconv.Itoa(tmpNum)
  789. lenStr := len(str)
  790. if lenStr > baseLen {
  791. newNumStr := str[0:baseLen]
  792. //fmt.Println("newNumStr:", newNumStr)
  793. newNumInt, _ := strconv.Atoi(newNumStr)
  794. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  795. newNum = -newNum
  796. if newNum < num {
  797. newNumInt -= 1
  798. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  799. newNum = -newNum
  800. }
  801. } else {
  802. newNum = float64(-tmpNum)
  803. }
  804. }
  805. return
  806. }
  807. // GetFloorNewNum 保留n位有效数字的向下取整
  808. // @params num 实际数据
  809. // @params baseLen 需要保留的有效位数
  810. func GetFloorNewNum(num float64, baseLen int) (newNum float64) {
  811. if num >= 1 {
  812. tmpNum := int(math.Floor(num)) // 向上取整
  813. str := strconv.Itoa(tmpNum)
  814. lenStr := len(str)
  815. if lenStr > baseLen {
  816. newNumStr := str[0:baseLen]
  817. newNumInt, _ := strconv.Atoi(newNumStr)
  818. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  819. if newNum < num {
  820. newNumInt -= 1
  821. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  822. }
  823. } else {
  824. newNum = float64(tmpNum)
  825. }
  826. return
  827. } else if num > 0 {
  828. // 这是小数
  829. str := strconv.FormatFloat(num, 'f', -1, 64)
  830. // 去除小数点和负号
  831. str = removeDecimalPoint(str)
  832. // 计算字符串长度
  833. lenStr := len(str)
  834. if lenStr > baseLen {
  835. newNumStr := str[0:baseLen]
  836. newNumInt, _ := strconv.Atoi(newNumStr)
  837. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  838. if newNum > num {
  839. newNumInt -= 1
  840. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  841. }
  842. } else {
  843. newNum = num
  844. }
  845. } else if num > -1 {
  846. // 这是小数
  847. str := strconv.FormatFloat(num, 'f', -1, 64)
  848. // 去除小数点和负号
  849. str = removeDecimalPoint(str)
  850. // 计算字符串长度
  851. lenStr := len(str)
  852. if lenStr > baseLen {
  853. newNumStr := str[0:baseLen]
  854. newNumInt, _ := strconv.Atoi(newNumStr)
  855. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  856. newNum = -newNum
  857. if newNum > num {
  858. newNumInt += 1
  859. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  860. newNum = -newNum
  861. }
  862. } else {
  863. newNum = num
  864. }
  865. if newNum == -0 {
  866. newNum = 0
  867. }
  868. } else { // 小于等于-1
  869. tmpNumFloat := math.Abs(num)
  870. tmpNum := int(math.Ceil(tmpNumFloat)) // 向上取整
  871. str := strconv.Itoa(tmpNum)
  872. lenStr := len(str)
  873. if lenStr > baseLen {
  874. newNumStr := str[0:baseLen]
  875. //fmt.Println("newNumStr:", newNumStr)
  876. newNumInt, _ := strconv.Atoi(newNumStr)
  877. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  878. newNum = -newNum
  879. if newNum > num {
  880. newNumInt += 1
  881. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  882. newNum = -newNum
  883. }
  884. } else {
  885. newNum = float64(-tmpNum)
  886. }
  887. }
  888. return
  889. }
  890. // 去除小数点和负号
  891. func removeDecimalPoint(str string) string {
  892. // 去除小数点
  893. str = str[strings.Index(str, ".")+1:]
  894. return str
  895. }
  896. func GetLocalIP() (ip string, err error) {
  897. addrs, err := net.InterfaceAddrs()
  898. if err != nil {
  899. return
  900. }
  901. for _, addr := range addrs {
  902. ipAddr, ok := addr.(*net.IPNet)
  903. if !ok {
  904. continue
  905. }
  906. if ipAddr.IP.IsLoopback() {
  907. continue
  908. }
  909. if !ipAddr.IP.IsGlobalUnicast() {
  910. continue
  911. }
  912. return ipAddr.IP.String(), nil
  913. }
  914. return
  915. }
  916. func GetDateByDateTypeV2(dateType int, tmpStartDate, tmpEndDate string, startYear int, latestDate time.Time) (startDate, endDate string) {
  917. startDate = tmpStartDate
  918. endDate = tmpEndDate
  919. switch dateType {
  920. case 1:
  921. startDate = "2000-01-01"
  922. endDate = ""
  923. case 2:
  924. startDate = "2010-01-01"
  925. endDate = ""
  926. case 3:
  927. startDate = "2015-01-01"
  928. endDate = ""
  929. case 4:
  930. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  931. startDate = "2021-01-01"
  932. endDate = ""
  933. case 5:
  934. //startDate = startDate + "-01"
  935. //endDate = endDate + "-01"
  936. case 6:
  937. //startDate = startDate + "-01"
  938. endDate = ""
  939. case 7:
  940. startDate = "2018-01-01"
  941. endDate = ""
  942. case 8:
  943. startDate = "2019-01-01"
  944. endDate = ""
  945. case 9:
  946. startDate = "2020-01-01"
  947. endDate = ""
  948. case 11:
  949. startDate = "2022-01-01"
  950. endDate = ""
  951. case 12:
  952. startDate = "2023-01-01"
  953. endDate = ""
  954. case 13:
  955. startDate = "2024-01-01"
  956. endDate = ""
  957. case DateTypeNYears:
  958. if startYear == 0 { //默认取最近5年
  959. startYear = 5
  960. }
  961. if latestDate.IsZero() {
  962. return
  963. }
  964. startDate = latestDate.AddDate(-startYear, 0, 0).Format(FormatDate)
  965. endDate = ""
  966. }
  967. // 兼容日期错误
  968. {
  969. if strings.Count(startDate, "-") == 1 {
  970. startDate = startDate + "-01"
  971. }
  972. if strings.Count(endDate, "-") == 1 {
  973. endDate = endDate + "-01"
  974. }
  975. }
  976. return
  977. }
  978. func GetColorMap() map[int]string {
  979. colorMap := make(map[int]string)
  980. colors := []string{"#0000FF", "#FF0000", "#999999", "#000000", "#7CB5EC", "#90ED7D", "#F7A35C", "#8085E9",
  981. "#F15C80", "#E4D354", "#2B908F", "#F45B5B", "#91E8E1", "#FDA8C7", "#8A4294",
  982. "#578B5A", "#0033FF", "#849EC1", "#FFDF0C", "#005496", "#00F0FF", "#4D535B",
  983. "#4F4C34", "#804141", "#86BABD", "#8AA3FF", "#960000", "#A173DB", "#A39340",
  984. "#CE814A", "#D1D2E6", "#EAB7B7", "#FF2E7A", "#FF4AF8", "#FF785B", "#FF9696", "#FFA800", "#FFBC97", "#FFDFDF"}
  985. for k, v := range colors {
  986. colorMap[k] = v
  987. }
  988. return colorMap
  989. }
  990. // GetDaysDiff1900 计算日期距离1900-01-01的天数
  991. func GetDaysDiff1900(date string) int {
  992. // 将字符串转换为时间类型
  993. //从1899年12月30日开始是因为Excel的日期计算是基于1900年1月1日的,而1900年并不是闰年,因此Excel日期计算存在一个错误。为了修正这个错误,
  994. //我们将时间回溯到1899年12月30日,这样在进行日期计算时可以正确地处理Excel日期。
  995. tStart, err := time.ParseInLocation(FormatDate, "1899-12-30", time.Local)
  996. if err != nil {
  997. return 0
  998. }
  999. tEnd, err := time.ParseInLocation(FormatDate, date, time.Local)
  1000. if err != nil {
  1001. return 0
  1002. }
  1003. // 计算两个日期之间的天数差值
  1004. duration := tEnd.Sub(tStart).Hours() / 24
  1005. days := int(duration)
  1006. return days
  1007. }
  1008. func ReplaceFormulaByTagMap(valTagMap map[string]int, formulaStr string) string {
  1009. funMap := getFormulaMap()
  1010. for k, v := range funMap {
  1011. formulaStr = strings.Replace(formulaStr, k, v, -1)
  1012. }
  1013. replaceCount := 0
  1014. for tag, val := range valTagMap {
  1015. dvStr := fmt.Sprintf("%v", val)
  1016. formulaStr = strings.Replace(formulaStr, tag, dvStr, -1)
  1017. replaceCount++
  1018. }
  1019. for k, v := range funMap {
  1020. formulaStr = strings.Replace(formulaStr, v, k, -1)
  1021. }
  1022. return formulaStr
  1023. }
  1024. // GetFrequencyEn 获取频度的英文版
  1025. func GetFrequencyEn(frequency string) (frequencyEn string) {
  1026. switch frequency {
  1027. case "日度":
  1028. frequencyEn = "day"
  1029. return
  1030. case "周度":
  1031. frequencyEn = "week"
  1032. return
  1033. case "旬度":
  1034. frequencyEn = "ten days"
  1035. return
  1036. case "月度":
  1037. frequencyEn = "month"
  1038. return
  1039. case "季度":
  1040. frequencyEn = "quarter"
  1041. return
  1042. case "年度":
  1043. frequencyEn = "year"
  1044. return
  1045. }
  1046. return
  1047. }
  1048. // DateConvMysqlConvMongo
  1049. // @Description: 将mysql中的日期比较符转换成mongo中的日期比较符
  1050. // @author: Roc
  1051. // @datetime 2024-05-08 11:03:26
  1052. // @param dateCon string
  1053. func DateConvMysqlConvMongo(dateCon string) string {
  1054. cond := ""
  1055. switch dateCon {
  1056. case "=":
  1057. cond = "$eq"
  1058. case "<":
  1059. cond = "$lt"
  1060. case "<=":
  1061. cond = "$lte"
  1062. case ">":
  1063. cond = "$gt"
  1064. case ">=":
  1065. cond = "$gte"
  1066. }
  1067. return cond
  1068. }
  1069. func DesBase64Decrypt(crypted []byte, desKey string) []byte {
  1070. result, _ := base64.StdEncoding.DecodeString(string(crypted))
  1071. remain := len(result) % 8
  1072. if remain > 0 {
  1073. mod := 8 - remain
  1074. for i := 0; i < mod; i++ {
  1075. result = append(result, 0)
  1076. }
  1077. }
  1078. origData, err := TripleDesDecrypt(result, []byte(desKey))
  1079. if err != nil {
  1080. panic(any(err))
  1081. }
  1082. return origData
  1083. }
  1084. // // 3DES解密
  1085. func TripleDesDecrypt(crypted, key []byte) ([]byte, error) {
  1086. block, err := des.NewTripleDESCipher(key)
  1087. if err != nil {
  1088. return nil, err
  1089. }
  1090. blockMode := cipher.NewCBCDecrypter(block, key[:8])
  1091. origData := make([]byte, len(crypted))
  1092. // origData := crypted
  1093. blockMode.CryptBlocks(origData, crypted)
  1094. origData = PKCS5UnPadding(origData)
  1095. // origData = ZeroUnPadding(origData)
  1096. return origData, nil
  1097. }
  1098. func PKCS5UnPadding(origData []byte) []byte {
  1099. length := len(origData)
  1100. // 去掉最后一个字节 unpadding 次
  1101. unpadding := int(origData[length-1])
  1102. return origData[:(length - unpadding)]
  1103. }
  1104. func TimeTransferString(format string, t time.Time) string {
  1105. str := t.Format(format)
  1106. if t.IsZero() {
  1107. return ""
  1108. }
  1109. return str
  1110. }
  1111. // handleSystemAppointDateT
  1112. // @Description: 处理系统日期相关的指定频率(所在周/旬/月/季/半年/年的最后/最早一天)
  1113. // @author: Roc
  1114. // @datetime2023-10-27 09:31:35
  1115. // @param Frequency string
  1116. // @param Day string
  1117. // @return date string
  1118. // @return err error
  1119. // @return errMsg string
  1120. func HandleSystemAppointDateT(currDate time.Time, appointDay, frequency string) (date string, err error, errMsg string) {
  1121. //currDate := time.Now()
  1122. switch frequency {
  1123. case "本周":
  1124. day := int(currDate.Weekday())
  1125. if day == 0 { // 周日
  1126. day = 7
  1127. }
  1128. num := 0
  1129. switch appointDay {
  1130. case "周一":
  1131. num = 1
  1132. case "周二":
  1133. num = 2
  1134. case "周三":
  1135. num = 3
  1136. case "周四":
  1137. num = 4
  1138. case "周五":
  1139. num = 5
  1140. case "周六":
  1141. num = 6
  1142. case "周日":
  1143. num = 7
  1144. }
  1145. day = num - day
  1146. date = currDate.AddDate(0, 0, day).Format(FormatDate)
  1147. case "本旬":
  1148. day := currDate.Day()
  1149. var tmpDate time.Time
  1150. switch appointDay {
  1151. case "第一天":
  1152. if day <= 10 {
  1153. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1154. } else if day <= 20 {
  1155. tmpDate = time.Date(currDate.Year(), currDate.Month(), 11, 0, 0, 0, 0, currDate.Location())
  1156. } else {
  1157. tmpDate = time.Date(currDate.Year(), currDate.Month(), 21, 0, 0, 0, 0, currDate.Location())
  1158. }
  1159. case "最后一天":
  1160. if day <= 10 {
  1161. tmpDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, currDate.Location())
  1162. } else if day <= 20 {
  1163. tmpDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, currDate.Location())
  1164. } else {
  1165. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1166. }
  1167. }
  1168. date = tmpDate.Format(FormatDate)
  1169. case "本月":
  1170. var tmpDate time.Time
  1171. switch appointDay {
  1172. case "第一天":
  1173. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1174. case "最后一天":
  1175. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1176. }
  1177. date = tmpDate.Format(FormatDate)
  1178. case "本季":
  1179. month := currDate.Month()
  1180. var tmpDate time.Time
  1181. switch appointDay {
  1182. case "第一天":
  1183. if month <= 3 {
  1184. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1185. } else if month <= 6 {
  1186. tmpDate = time.Date(currDate.Year(), 4, 1, 0, 0, 0, 0, currDate.Location())
  1187. } else if month <= 9 {
  1188. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1189. } else {
  1190. tmpDate = time.Date(currDate.Year(), 10, 1, 0, 0, 0, 0, currDate.Location())
  1191. }
  1192. case "最后一天":
  1193. if month <= 3 {
  1194. tmpDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, currDate.Location())
  1195. } else if month <= 6 {
  1196. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1197. } else if month <= 9 {
  1198. tmpDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, currDate.Location())
  1199. } else {
  1200. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1201. }
  1202. }
  1203. date = tmpDate.Format(FormatDate)
  1204. case "本半年":
  1205. month := currDate.Month()
  1206. var tmpDate time.Time
  1207. switch appointDay {
  1208. case "第一天":
  1209. if month <= 6 {
  1210. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1211. } else {
  1212. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1213. }
  1214. case "最后一天":
  1215. if month <= 6 {
  1216. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1217. } else {
  1218. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1219. }
  1220. }
  1221. date = tmpDate.Format(FormatDate)
  1222. case "本年":
  1223. var tmpDate time.Time
  1224. switch appointDay {
  1225. case "第一天":
  1226. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1227. case "最后一天":
  1228. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1229. }
  1230. date = tmpDate.Format(FormatDate)
  1231. default:
  1232. errMsg = "错误的日期频度:" + frequency
  1233. err = errors.New(errMsg)
  1234. return
  1235. }
  1236. return
  1237. }
  1238. func CompareFloatByOpStrings(op string, a, b float64) bool {
  1239. switch op {
  1240. case "=":
  1241. return a == b
  1242. case ">":
  1243. return a > b
  1244. case ">=":
  1245. return a >= b
  1246. case "<=":
  1247. return a <= b
  1248. case "<":
  1249. return a < b
  1250. }
  1251. return false
  1252. }
  1253. // RoundNumber 保留小数位数
  1254. func RoundNumber(num string, decimalPlaces int, hasPercent bool) string {
  1255. numDecimal, _ := decimal.NewFromString(num)
  1256. if hasPercent {
  1257. numDecimal = numDecimal.Mul(decimal.NewFromInt(100))
  1258. }
  1259. numStr := numDecimal.Round(int32(decimalPlaces)).StringFixed(int32(decimalPlaces))
  1260. if hasPercent {
  1261. numStr += "%"
  1262. }
  1263. return numStr
  1264. }