common.go 34 KB

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